Skip to main content
1 of 2
gerrit
  • 25.6k
  • 17
  • 104
  • 180

To expand on gruszczys answer, I have used a pattern like:

class X:
    x = None
    y = None
    z = None
    def __init__(self, **kwargs):
        for (k, v) in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)
            else:
                raise TypeError('Unknown keyword argument: {:s}'.format(k))

I like this method because it:

  • avoids repetition
  • is resistant against typos when constructing an object
  • works well with subclassing (can just super().__init(...))
  • allows for documentation of the attributes on a class-level (where they belong) rather than in X.__init__

It could probably be improved upon a bit, but I'm the only user of my own code so I am not worried about any form of input sanitation.

gerrit
  • 25.6k
  • 17
  • 104
  • 180