Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: unpack init args into member variables cleanly

Tags:

python

setattr

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.

like image 244
BoltzmannBrain Avatar asked Mar 02 '26 22:03

BoltzmannBrain


1 Answers

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.

like image 60
wim Avatar answered Mar 05 '26 11:03

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!