saving constructor arguments automatically
Question: Frequently the constructor of a class will take it's arguments and save them
on the instance. For example:

    
    
    class Example(object):
        def __init__(self, title='',backtitle='', height=20, width=50):
            self.title = title
            self.backtitle = backtitle
            self.height = height
            self.width = width
    

This is repetitious so I made a helper function to do this automatically:

    
    
    from inspect import getargspec
    def save_args(values):
        for i in getargspec(values['self'].__init__).args[1:]:
            values['self'].__dict__[i] = values[i]
    
    class Example(object):
        def __init__(self, title='',backtitle='', height=20, width=50):
            save_args(vars())
    

My questions are as follows:

  * Will this fail with certain classes or agruments
  * Is it portable, will it work on Jython, etc.. It worked for me on python 2.7 and 3.2
  * Is there a simpler alternative?
  * Is there a python package out there that already does this? 


Answer: It'll fail when your class uses
[`__slots__`](http://docs.python.org/3/reference/datamodel.html#slots). You
could use
[`setattr()`](http://docs.python.org/3/library/functions.html#setattr)
instead:

    
    
    from inspect import getargspec
    def save_args(values):
        for i in getargspec(values['self'].__init__).args[1:]:
            setattr(values['self'], i, values[i])
    

provided the arguments keyword arguments to `__init__` are all declared slots
of course.

Otherwise this should work on any Python implementation.

You may be interested in a [previous discussion of the
topic](http://stackoverflow.com/q/1389180), which sparked a [Python-ideas list
thread](http://mail.python.org/pipermail/python-
ideas/2011-April/thread.html#9930).

