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

bruceg113355 at gmail.com bruceg113355 at gmail.com
Fri Nov 16 16:00:37 CET 2012


On Thursday, November 15, 2012 11:16:08 PM UTC-5, Ethan Furman wrote:
> Emile van Sebille 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):
> 
> so this line ^ becomes
> 
>         def wrapper(*args, **kwargs):
> 
> >>         args = (arg.replace('_', '') for arg in args)
> 
> and add a line
> 
>             for k, v in kwargs:
> 
>                 kwargs[k] = v.replace('_', '')
> 
> >>         return fn(*args)
> 
> and this line ^ becomes
> 
>             return fn(*args, **kwargs)
> 
> >>     return wrapper
> 
> 
> 
> ~Ethan~


Ethan,

I tried you code suggestions but got errors.
However, this works:

from functools import wraps

def fix_args(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs): 
        args = (arg.replace('_', '') for arg in args)
        for kv in kwargs:
            kwargs[kv] = kwargs[kv].replace('_', '')         
        return fn(*args, **kwargs) 
    return wrapper
   
@fix_args
def foo(a1="", a2="", b1="", b2=""):
     print(a1)
     print(a2)
     print(b1)
     print(b2)
     print ""
     
    
     
foo ('a1a1_x', 'a2a2_x', 'b1b1_x', 'b2b2_____x')
foo (a1='a1a1_x', a2='a2a2_x', b1='b1b1_x', b2='b2b2_____x') 
foo ('a1a1_x', 'a2a2_x', b1='b1b1_x', b2='b2b2_____x') 

Bruce





More information about the Python-list mailing list