Is there are good DRY fix for this painful design pattern?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Feb 26 23:46:57 EST 2018
On Mon, 26 Feb 2018 17:39:43 +0100, Peter Otten wrote:
[...]
> I have not yet looked into dataclasses. Don't they handle the __init__()
> part? Anyway, here's my attempt to make spam() less spammy:
I'm not too concerned about __init__, it's only one method :-)
> $ cat attrs_to_args_decorator.py
> import functools
> import inspect
>
> def add_defaults(f):
> argnames = inspect.getfullargspec(f).args[1:]
>
> @functools.wraps(f)
> def wrapper(self, *args, **kw):
> args = [
> getattr(self, name) if value is None else value for name,
> value in zip(argnames, args)
> ]
> for name in argnames[len(args):]:
> if name not in kw or kw[name] is None:
> kw[name] = getattr(self, name)
> return f(self, *args, **kw)
> return wrapper
[...]
Interesting, this does look promising, thanks.
--
Steve
More information about the Python-list
mailing list