Is there a simpler way to modify all arguments in a function before using the arguments?
__peter__ at web.de
Sun Nov 11 10:28:55 CET 2012
> In article <mailman.3530.1352538537.27098.python-list at python.org>,
> Peter Otten <__peter__ at web.de> wrote:
>>Miki Tebeka wrote:
>>>> Is there a simpler way to modify all arguments in a function before
>>>> using the arguments?
>>> You can use a decorator:
>>> from functools import wraps
>>> def fix_args(fn):
>>> def wrapper(*args):
>>> args = (arg.replace('_', '') for arg in args)
>>> return fn(*args)
>>> return wrapper
>>> def foo(x, y):
>>I was tempted to post that myself, but he said /simpler/ ;)
> From my POV, that *is* simpler. When you change the parameters for foo,
> you don't need to change the arg pre-processing. Also allows code reuse,
> probably any program needing this kind of processing once will need it
Typical changes would be
def bar(x, y=None):
def baz(file, x, y):
Do you find it obvious what
print? Do you find the traceback produced by the latter helpful?
Moving complexity into a helper function often makes client code simpler
because if the helper is well-tested and preferrably maintained by someone
else the part that you have to deal with becomes simpler, but the overall
complexity still increases.
A fix_args() decorator is worthwhile only if you need it more than once or
twice, and because it is hard to generalise I expect that yagni.
More information about the Python-list