3 ms·
A dataclass is just a class where all it does is fill internal attributes (lots of self.x = "foo"). To fill a dataclass from kwargs, instead of: def __init__
by idealmedtech 5y ago
A dataclass is just a class where all it does is fill internal attributes (lots of self.x = "foo"). To fill a dataclass from kwargs, instead of:
def __init__(self, x=None, y=None):
self.x = x
self.y = y
You can do:
def __init__(self, **kwargs):
self.__dict__.update(kwargs) # This may be **kwargs, I'm fuzzy on it
With this, the following code works with both:
myObj = MyClass(x=1, y=2)
Now, you might say "but with the kwargs method you can add _ANY_ attribute not just x and y!"
That's precisely the point. When you're still iterating on the ergonomics, you want the ability to add new things without repeating a bunch of boilerplate. Once you've figured out what those look like, you can and should go back and fix the names in stone.
- bitcoinmoney 5y agoWhat kind of style/idiom is this ? And what industry/space do you usually see this practice? Is it common? Just genuinely curious because my python is only used for scripting/pandas.
- saila 5y agoI was looking for an example of using locals() to "fill a data class from kwargs" or something similar to that. The example here doesn't use locals(). That aside, I generally wouldn't use the kwargs approach shown in this example either. I'd use https://docs.python.org/3/library/dataclasses.html https://docs.python.org/3/library/dataclasses.html or https://www.attrs.org/ https://www.attrs.org/ instead.