Is there a simpler way to modify all arguments in a function before using the arguments?

Peter Otten __peter__ at web.de
Sun Nov 11 04:28:55 EST 2012


Aahz wrote:

> 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):
>>>     @wraps(fn)
>>>     def wrapper(*args):
>>>         args = (arg.replace('_', '') for arg in args)
>>>         return fn(*args)
>>> 
>>>     return wrapper
>>> 
>>> @fix_args
>>> def foo(x, y):
>>>     print(x)
>>>     print(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
> again.

Typical changes would be

@fix_args
def bar(x, y=None):
    print(x)
    print(y)

@fix_args
def baz(file, x, y):
    print(s, file=file)

Do you find it obvious what 

bar("a_b")
bar("a_b", y="c_d")

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 mailing list