On Wed, 6 May 2020 at 18:56, Lewis Ball
Joao S. O. Bueno wrote:
Here - with the current inspect.Signature, it is straightforward to get a decorator that can do that covering most, if not all, corner cases, and even adding some extra functionality: https://gist.github.com/jsbueno/f689a181d50384f627b43b9b2aabe4f2
from inspect import signature, Parameter from functools import wraps, partial
def autoassign(func=None, *, expand_kwargs=False):
if not func: return partial(autoassign, expand_kwargs=expand_kwargs) sig = signature(func) @wraps(func) def wrapper(*args, **kwargs): instance = args[0] bound_args = sig.bind(*args, **kwargs) bound_args.apply_defaults() for i, (key, value) in enumerate(bound_args.arguments.items()): if i == 0 or sig.parameters[key].kind == Parameter.POSITIONAL_ONLY: continue if expand_kwargs and sig.parameters[key].kind == Parameter.VAR_KEYWORD: for kwkey, kwvalue in value.items(): setattr(instance, kwkey, kwvalue) continue setattr(instance, key, value) return func(*args, **kwargs) return wrapper
""" class A: @autoassign def __init__(self, a, b, c=3): pass
a = A(1, 2) assert a.a == 1 and a.b == 2 and a.c == 3 """
Is there a good reason to exclude positional only args from this? I imagine if you are passing them to init you still want them to be treated internally in the same way as the other args.
I think he idea of positional only args is that you don't want whoever is calling you to care about the variable names they will have inside your code whatsoever. If you don't care about the name - (ideally, introspection tools should even hide this name, if they have a suitable notation) - you can't care about the attribute that is created. Even if they are to be stored as passed in attributes, the semantics for them would be of "private" attributes - for which one can do the assignment manually.
Could we put this into the standard library, so that IDEs and linters are programmed to recognise it?
Some people on this thread seem to have liked this approach - of course I'd like and help getting this into the stdlib if it has support. And yes, you come to an interesting point there - while this could easily rest in pypi - linters and ide's might complain about "attributes not being assigned in __init__" Otherwise, I can get a Pypi package with this, and a few other bells and whistles along.
I agree, without this being recognised by linters/IDEs any attrs will show with ugly warnings which would stop anyone from using it. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/IMBONG... Code of Conduct: http://python.org/psf/codeofconduct/