Differences between functools.partial and a similar lambda?

a 夏天 提交于 2019-11-28 09:13:43
Sven Marnach
  1. A lambda function has the same type as a standard function, so it will behave like an instance method.

  2. The partial object in your example can be called like this:

    g1(x, y, z)
    

    leading to this call (not valid Python syntax, but you get the idea):

    f(*secondary_args, x, y, z, **secondary_kwargs)
    

    The lambda only accepts a single argument and uses a different argument order. (Of course both of these differences can be overcome – I'm just answering what the differences between the two versions you gave are.)

  3. Execution of the partial object is slightly faster than execution of the equivalent lambda.

I believe that the class method thing only applies to functions assigned during class definition. Functions assigned later are not treated specially.

Other than that, I'd personally favor lambdas since they're more common and hence make the code easier to understand.

class Foo(object):
    def __init__(self, base):
        self.int = lambda x:int(x, base)

print Foo(4).int('11')

Yes, lambda will "suffer" from this. partial doesn't have this problem because it is an object with the call operator overloaded, rather than a real function.

But using a lambda like this in a class definition is just misuse.

partials are not only about 20% faster than equivalent lambdas as already said but they keep a direct ref to they function the relate to. While in lambdas that function is 'burried' within the function body.

=> If you need to only solve the problem of defering evaluation of one function until all args are known then use partials. You'll have way better introspection methods compared to bury the calls into anonymous functions, i.e. lambdas.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!