0

The Python 3.7.2 documentation on the asyncio eventloop says in the documentation of the call_later function:

The optional positional args will be passed to the callback when it is called. If you want the callback to be called with keyword arguments use functools.partial().

Is using functools.partial considered superior to using lambda for this case?

jan
  • 1,408
  • 13
  • 19
  • 2
    `partial` will 'freeze' the arguments, which can help avoid a common mistake. See https://docs.python-guide.org/writing/gotchas/#late-binding-closures – Alex Hall Feb 25 '19 at 16:28

1 Answers1

1

Is using functools.partial considered superior to using lambda for this case?

"Superior" is too strong a word. It might be correct to say that functools.partial is the "one obvious choice" for simple argument binding.

Some possible advantages of functools.partial compared to lambda not implied by the above sentence:

  • As pointed out by @AlexHall, functools.partial avoids the late binding mistake that often occurs when the lambda is created in a loop.

  • functools.partial might make the intent clearer to some readers. (This is obviously individual, as readers with any FP background will typically have a strong preference for lambda.)

  • In CPython functools.partial might be a tiny bit faster than lambda because it doesn't need to create a Python stack frame, nor does it need to perform the actual binding; its optimized C implementation just needs to execute the call on the object. The difference should be measured on a case-by-case basis.

user4815162342
  • 141,790
  • 18
  • 296
  • 355