Is there a simpler way to modify all arguments in a function before using the arguments?
brucegoodstein at gmail.com
brucegoodstein at gmail.com
Thu Nov 15 18:20:10 EST 2012
On Saturday, November 10, 2012 10:35:12 AM UTC-5, 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.
>
> --
>
> Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
>
>
>
> "....Normal is what cuts off your sixth finger and your tail..." --Siobhan
Using a decorator works when named arguments are not used. When named arguments are used, unexpected keyword error is reported. Is there a simple fix?
Thanks to all,
Bruce
Code:
-----
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(a1="", a2="", b1="", b2=""):
print(a1)
print(a2)
print(b1)
print(b2)
foo ('a1a1_x', 'a2a2_x', 'b1b1_x', 'b2b2_____x')
foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_____x')
Results:
--------
a1a1x
a2a2x
b1b1x
b2b2x
Traceback (most recent call last):
File "C:\WORK\masterDB_Update\argtest.py", line 19, in <module>
foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_____x')
TypeError: wrapper() got an unexpected keyword argument 'a1'
More information about the Python-list
mailing list