Nested Function Question

GZ zyzhu2000 at gmail.com
Fri Jan 6 16:46:16 EST 2012


Hi,

I am reading the documentation of functools.partial (http://
docs.python.org/library/functools.html#functools.partial) and found
the following 'reference implementation' of functools.partial.

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

I don't understand why the below 3 lines are needed:

    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords


It is as if they are trying to prevent garbage collection, but I don't
get why it is needed. As long as something holds reference to newfunc,
because it in turn references keywords and args, nothing will be
freed. If nothing is referencing newfunc, then everything should be
freed.

Thanks,
GZ



More information about the Python-list mailing list