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.
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:
__init__, it's time to refactor. If you'd like to experiment with libraries to remove that duplication, check out python-fields, or the slightly less magical attrs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With