I see patterns like
def __init__(self, x, y, z):
...
self.x = x
self.y = y
self.z = z
...
quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should the class inherit from namedtuple
instead?
You could also do:
Of course, you would have to import the
inspect
module.Python 3.7 onwards
In Python 3.7, you may (ab)use the
dataclass
decorator, available from thedataclasses
module. From the documentation:If your class is large and complex, it may be inappropriate to use a
dataclass
. I'm writing this on the day of release of Python 3.7.0, so usage patterns are not yet well established.It's a natural way to do things in Python. Don't try to invent something more clever, it will lead to overly clever code that no one on your team will understand. If you want to be a team player and then keep writing it this way.
An interesting library that handles this (and avoids a lot of other boilerplate) is attrs. Your example, for instance, could be reduced to this (assume the class is called
MyClass
):You don't even need an
__init__
method anymore, unless it does other stuff as well. Here's a nice introduction by Glyph Lefkowitz.As others have mentioned, the repetition isn't bad, but in some cases a namedtuple can be a great fit for this type of issue. This avoids using locals() or kwargs, which are usually a bad idea.
I've found limited use for it, but you can inherit a namedtuple as with any other object (example continued):