4 ms·
I personally wouldn't let any usage of locals() through code review, except perhaps in some extremely rare circumstance. Do you have an example of "filling a d
by saila 5y ago
I personally wouldn't let any usage of locals() through code review, except perhaps in some extremely rare circumstance.
Do you have an example of "filling a data class from kwargs"?
- musingsole 5y agoConcretely, why?
- idealmedtech 5y agoA 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.