10
votes

I've got fed up of continually typing the same, repetitive commands over and over again in my __init__ function. I was wondering if I could write a decorator to do the work for me. Here's an example of my question:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

Is there some way in which I can automatically have all arguments passed into the function become instance variables with the same names? For example:

class Point:
    @instance_variables
    def __init__(self, x, y):
        pass

Where @instance_variables would automatically set self.x = x and self.y = y. How could I do this?
Thanks!

EDIT: I should mention that I use CPython 2.7.

7
This seems like it would be such a useful tool I imagine that there is some 3rd party library on PyPI that provides this functionality. - SethMMorton
@SethMMorton I disagree that this is useful. I find that forcing developers (including myself) to type out the painful boilerplate of member variable initiation is a good way to deter people from having __init__ methods that accept a ridiculous number of arguments, which are turned into a ridiculous number of member variables. It's like a tax on class bloatedness. If you find yourself accepting so many args in __init__ that you need this feature, it's usually a good indicator that you should refactor your design with smaller, compartmentalized classes, maybe a MixIn design. - ely
Still willing to go this way? As Ashwin said, a reliable decorator-type solution turns out to be rather ugly and ineffective in comparison with a few lines of code. - ivan_pozdeev

7 Answers

4
votes

Here is my first try at the decorator:

[EDIT second try: I added handling defaults for variables and checking for valid keywords. Thanks ivan_pozdeev ]

[EDIT 3: Added check for defaults is not None]

def instanceVariables(func):
    def returnFunc(*args, **kwargs):
        selfVar = args[0]

        argSpec = inspect.getargspec(func)
        argumentNames = argSpec[0][1:]
        defaults = argSpec[3]
        if defaults is not None:
            defaultArgDict = dict(zip(reversed(argumentNames), reversed(defaults)))
            selfVar.__dict__.update(defaultArgDict)

        argDict = dict(zip(argumentNames, args[1:]))
        selfVar.__dict__.update(argDict)


        validKeywords = set(kwargs) & set(argumentNames)
        kwargDict = {k: kwargs[k] for k in validKeywords}
        selfVar.__dict__.update(kwargDict)

        func(*args, **kwargs)

    return returnFunc

Here is a example:

class Test():

    @instanceVariables
    def __init__(self, x, y=100, z=200):
        pass

    def printStr(self):
        print(self.x, self.y, self.z)

a = Test(1, z=2)

a.printStr()

>>> 1 100 2
2
votes

I disagree that this is useful. I find that forcing developers (including myself) to type out the painful boilerplate of member variable initiation is a good way to deter people from having __init__ methods that accept a ridiculous number of arguments, which are turned into a ridiculous number of member variables.

This happens a lot when someone wants to extend the features available in a class through the use of extra arguments, feature flags, and boolean switch variables that control customized instantiation. I consider all of those to be deficient ways to handle the need for accommodating new or optional extended complexity.

Being required to type out this particular kind of boilerplate is like a tax on class bloatedness. If you find yourself accepting so many args in __init__ that you need this feature, it's usually a good indicator that you should refactor your design with smaller, compartmentalized classes, maybe a MixIn design.

Nonetheless, here is one way to do it without the misdirection of the decorator. I didn't make an attempt to handle *args but then again in this particular case you would have to define special logic for what unnamed positional arguments meant anyway.

def init_from_map(obj, map):
    for k,v in map.iteritems():
        if k not in ["self", "kwargs"]:
            setattr(obj, k, v)
        elif k == "kwargs":
            for kk, vv in v.iteritems():
                setattr(obj, kk, vv)

class Foo(object):
    def __init__(self, x, y, **kwargs):
        init_from_map(self, locals())

f = Foo(1, 2, z=3)
print f.x, f.y, f.z
print f.__dict__

Prints:

1 2 3
{'x': 1, 'y': 2, 'z': 3}
2
votes

For those who might find this post, but are interested in a Python 3.7+ solution (and as Python 2 End Of Life is the Jan 1, 2020 ;-), you can use the Python standard lib dataclasses.

from dataclasses import dataclass

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

Will add, among other things, a __init__() that looks like:

def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand
1
votes

You could do this:

def __init__(self, x, y):
    self.__dict__.update(locals())
    del self.self   # redundant (and a circular reference)

But this is probably not a real improvement, readability-wise.

0
votes

For Python 3.3+:

from functools import wraps
from inspect import Parameter, signature


def instance_variables(f):
    sig = signature(f)
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        values = sig.bind(self, *args, **kwargs)
        for k, p in sig.parameters.items():
            if k != 'self':
                if k in values.arguments:
                    val = values.arguments[k]
                    if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
                        setattr(self, k, val)
                    elif p.kind == Parameter.VAR_KEYWORD:
                        for k, v in values.arguments[k].items():
                            setattr(self, k, v) 
                else:
                    setattr(self, k, p.default) 
    return wrapper

class Point(object):
    @instance_variables 
    def __init__(self, x, y, z=1, *, m='meh', **kwargs):
        pass

Demo:

>>> p = Point('foo', 'bar', r=100, u=200)
>>> p.x, p.y, p.z, p.m, p.r, p.u
('foo', 'bar', 1, 'meh', 100, 200)

A non-decorator approach for both Python 2 and 3 using frames:

import inspect


def populate_self(self):
    frame = inspect.getouterframes(inspect.currentframe())[1][0]
    for k, v in frame.f_locals.items():
        if k != 'self':
            setattr(self, k, v)


class Point(object):
    def __init__(self, x, y):
        populate_self(self)

Demo:

>>> p = Point('foo', 'bar')
>>> p.x
'foo'
>>> p.y
'bar'
0
votes

You can either use reflection to reduce code duplication

self.__dict__.update(v,locals()[v] for v in 'x','y')

(or almost equivalent (v must not be a meta-variable name))

for v in 'x','y': setattr(self,v,locals()[v])

Or use CPython's implementation details to retrieve argument names from runtime as per Getting method parameter names in python

cur_fr = sys._getframe().f_code
self.__dict__.update(v,locals()[v] for v in cur_fr.co_varnames[1:cur_fr.co_argcount])  # cur_fr.f_locals is the same as locals()

The 2nd approach appears more "automated" but, as I've said, it turns out to be rather inflexible. If your argument list is longer than 3-4, you probably only need to handle some of the arguments this way, in which case, you have no other options but to construct their list by hand.

0
votes

I am searching for an autoinit decorator and come across this thread. I couldn't find any @autoinit in the web that handles variable arguments, variable keywords and the keyword-only arguments. Inspired by the other solutions, I wrote my own version that support everything.

I did some testing, it seems to work fine in all scenarios, but I haven't exhaustively test the code. Let me know if it has a bug. Thanks.

def autoinit(func):
"""
This decorator function auto initialize class variables from __init__() arguments
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
    if func.__name__ != '__init__':
        return func(*args, **kwargs)

    self = args[0]
    func_spec = inspect.getfullargspec(func)

    # initialize default values
    nargs = dict()
    if func_spec.kwonlydefaults is not None:
        for k,v in func_spec.kwonlydefaults.items():
            nargs[k] = v
    if func_spec.defaults is not None:
        for k,v in zip(reversed(func_spec.args), reversed(func_spec.defaults)):
            nargs[k] = v
    if func_spec.varargs is not None:
        nargs[func_spec.varargs] = []
    if func_spec.varkw is not None:
        nargs[func_spec.varkw] = {}
    # fill in positional arguments
    for index, v in enumerate(args[1:]):
        if index+1 < len(func_spec.args):
            nargs[func_spec.args[index+1]] = v
        elif func_spec.varargs is not None:
            # variable argument
            nargs[func_spec.varargs].append(v)
    # fill in keyword arguments
    for k,v in kwargs.items():
        if k in itertools.chain(func_spec.args, func_spec.kwonlyargs):
            nargs[k] = v
        elif func_spec.varkw is not None:
            # variable keywords
            nargs[func_spec.varkw][k] = v

    # set values to instance attributes
    for k,v in nargs.items():
        setattr(self, k, v)
    return func(*args, **kwargs)
return wrapper