kw param question

Albert Hopkins marduk at letterboxes.org
Mon Aug 3 22:27:34 CEST 2009


On Mon, 2009-08-03 at 19:59 +0000, kj wrote:
> 
> I want to write a decorator that, among other things, returns a
> function that has one additional keyword parameter, say foo=None.
> 
> When I try
> 
> def my_decorator(f):
>     # blah, blah
>     def wrapper(*p, foo=None, **kw):
>         x = f(*p, **kw)
>         if (foo):
>             # blah, blah
>         else
>             # blah blah
>     return wrapper 
> 
> ...i get a syntax error where it says "foo=None".  I get similar
> errors with everything else I've tried.
> 

Not exactly sure what you're trying to do.. but, regular arguments must
be used *before* positional and keyword arguments so the definition:

    def wrapper(*p, foo=None, **kw):

is syntactically incorrect whereby the following is correct:

   def wrapper(foo=None, *p, **kw):

But if what you are wanting is to actually add 'foo' to kw then I would
do this:

def my_decorator(f):
    # blah, blah
    def wrapper(*p, **kw):
        if 'foo' not in kw:
            kw['foo'] = None
        x = f(*p, **kw)
        if kw['foo']:
            # blah blah
        else:
            # blah blah
    return wrapper 






More information about the Python-list mailing list