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

Emile van Sebille emile at fenx.com
Thu Nov 15 19:03:27 EST 2012


brucegoodstein at gmail.com wrote:

> 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?

Extend def wrapper(*args) to handle *kwargs as well

Emile

> 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