
Le 26/04/17 à 13:12, Brice PARENT a écrit :
Why not simply do this :
class MyClass: def _set_multiple(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value)
def __init__(self, a, b, c): self._set_multiple(a=a, b=b, c=c)
-> No new syntax, no inspection, simple to read, parse and understand, and explicit.
And you could directly do some simple cleanings or not define a variable, like :
class MyClass: def _set_multiple(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value)
def __init__(self, a, b, c): self._set_multiple(a=a * 2, b=clean_field(b))
- Brice Also, a new syntax that could be useful in many other ways, while being easy to understand to any pythonista, would be : class MyClass: def __init__(self, a, b, c): self.(a, b, c) = a, b, c
You still have to type twice the name of the variable instead of one though, if you don't want to use *args and **kwargs, but you still save the same vertical space with something efficient and way more useful. It is currently an invalid syntax, but that allows to be sure that it doesn't break old source code and doesn't require any deprecation. As a new syntax, it can probably be optimized a lot at the implementation level. It can be used with *args and **kwargs also, ... class MyClass: def __init__(self, *args, **kwargs): self.(a, b, c) = args self.(*kwargs.keys()) = kwargs.values() # or self.(kwargs.keys()) = kwargs.values() ... on instantiated objects (so not only in self), ... background_color.('r', 'g', 'b') = 255, 127, 0 ... update the values to be stored on-the-fly, ... class MyClass: def __init__(self, a, b, c): self.(a, b, c) = a, b * 2.54, c ... make any validation you want, ... class MyClass: def __init__(self, a, b, c): if c > 10: b = 0 elif c < 0: raise ValidationError("c can't be lower than 0") self.(a, b, c) = a, b, c ... update the names of the attributes and insert names that weren't in the signature ... class MyClass: def __init__(self, a, b, c): self.(a, b, _c, uuid) = a, b, c, str(uuid.uuid4()) Morality : This is a completely other thing to what's proposed here, even if it does solve more or less OP's initial problem. It's open to discussion whether it's useful or not, but it allows some kind of unpacking at the classes properties level, not exclusively into active scope. - Brice