scope of function parameters (take two)

Ian Kelly ian.g.kelly at gmail.com
Tue May 31 12:16:12 EDT 2011


On Tue, May 31, 2011 at 1:38 AM, Daniel Kluev <dan.kluev at gmail.com> wrote:
> @decorator.decorator
> def copy_args(f, *args, **kw):
>    nargs = []
>    for arg in args:
>        nargs.append(copy.deepcopy(arg))
>    nkw = {}
>    for k,v in kw.iteritems():
>        nkw[k] = copy.deepcopy(v)
>    return f(*nargs, **nkw)

There is no "decorator" module in the standard library.  This must be
some third-party module.  The usual way to do this would be:

def copy_args(f):
    @functools.wraps(f)
    def wrapper(*args, **kw):
        nargs = map(copy.deepcopy, args)
        nkw = dict(zip(kw.keys(), map(copy.deepcopy, kw.values())))
        return f(*nargs, **nkw)
    return wrapper

Note that this will always work, whereas the "decorator.decorator"
version will break if the decorated function happens to take a keyword
argument named "f".

Cheers,
Ian



More information about the Python-list mailing list