3

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.

Community
  • 1
  • 1
BoltzmannBrain
  • 5,082
  • 11
  • 46
  • 79

1 Answers1

3

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.

wim
  • 338,267
  • 99
  • 616
  • 750
  • Any suggestions for a built-in data structure? – BoltzmannBrain Mar 15 '17 at 03:13
  • I can't really suggest something without more information about your requirements or use-case. When in doubt, just use a `dict`. If you really want getattr-style access instead of getitem-style access, you can use the `Namespace` class that comes for free in the `argparse` module. And `namedtuple` works fine, really, just don't look at how that's implemented because it's hideous. – wim Mar 15 '17 at 03:16
  • 1
    I like the way this addresses the [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and focuses the culprit: too many parameters for a single function. – TigerhawkT3 Mar 15 '17 at 03:26