Search code examples
pythonsetattr

Python: unpack init args into member variables cleanly


Consider the example class below:

class Foo(object):
    def __init__(self, a=2, b=0, c=1, d=42):
        self.a = a
        self.b = b
        self.c = c
        self.d = d

Is there a clean way to unpack the kwargs into member variables? Perhaps this example is trivial, but imagine a constructor with 17 member variables of long names like redundant_data_structure_that_we_should_probably_remove. I'm aware of setattr(), for example in this other question, but I don't want to accept **kwargs in the constructor -- that is, I'd like to unpack only the defined member vars a, b, c, and d.


Solution

  • I've looked at this before, and concluded there's no nice way to automate out the boilerplate.

    Fortunately, you usually don't need it:

    • If you have 17 member variables passed in the __init__, it's time to refactor.
    • If your class is only just a namespace / bag of data, don't use a class in the first place.

    If you'd like to experiment with libraries to remove that duplication, check out python-fields, or the slightly less magical attrs.