简体   繁体   English

使用functools.partial()是否需要付费?

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

The higher-order function functools.partial() can create a new function as follows: 高阶函数functools.partial()可以创建一个新函数,如下所示:

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? functools.partial()是否实际上创建了一个不需要调用f的新函数,或者它们是否相同?

> 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: 这是python 3.4中functools.partial的源代码:

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. 在顶部,它定义了纯python后备版本,在底部,它尝试导入C版本。 You can find the C code here . 您可以在此处找到C代码。

Here is the current implementation of partial . 这是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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