Happy to be proven wrong and learn something though!
Happy to be proven wrong and learn something though!
Do you have an example of "filling a data class from kwargs"?
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.
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 or https://www.attrs.org/ instead.
Maybe this is the use-case you're talking about, but when I have something super generic I usually have clear and careful error handling inside. It kind of defeats the terseness of using locals(), but the goal is more about flexibility.
# You can use local variables as the dictionary
title="..."
isbn="...."
cursor.execute(sql, locals())
In the pre-dataclass / pre-namedtuple days I would use: class Spam:
def __init__(a=1, b=2, c=3, d="four", .. lots args ..):
self.__dict__.update(locals())
del self.self
in prototype code. But that wouldn't go into production. (I wouldn't put the namedtuple version in production either.)