简体   繁体   中英

Is there a cost to using functools.partial()?

The higher-order function functools.partial() can create a new function as follows:

newf(arg1) = functools.partial( f, arg1, val )

which is obviously equivalent to just saying

def newf(arg1): return f( arg1, val )

in terms of what they do. But what about performance? Does functools.partial() actually create a new function that does not need to call f or are they identical?

> import functools
> def nop():
...:     pass
...: 

> %timeit nop()
10000000 loops, best of 3: 63.5 ns per loop

> %timeit functools.partial(nop)()
1000000 loops, best of 3: 205 ns per loop

So I would say it looks pretty trivial unless you are doing something silly. And we can get most of that back if we're going to be calling the partial multiple times:

> f = functools.partial(nop)
> %timeit f()
10000000 loops, best of 3: 86.7 ns per loop

This is the source code of functools.partial in python 3.4:

def partial(func, *args, **keywords):
    """New function with partial application of the given arguments
    and 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

try:
    from _functools import partial
except ImportError:
    pass

on the top it defines a purely python fall-back version, and on the bottom it tries to import the C version. You can find the C code here .

Here is the current implementation of partial .

Do you understand it? Else ask, but i found it very hard to explain cleanly because of all the inner and outer functions.

def partial(func, *args, **keywords):
    """New function with partial application of the given arguments
    and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM