Jun-22-2023, 02:51 PM
When you use a variable in a lambda expression, the expression creates a closure, an expression, and the relevant context required to evaluate the expression. In this example, the lambda expression "p" creates a closure that contain the variables x and y.
Output:Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 0
>>> y = 0
>>> p = lambda: print(x, y)
>>> p()
0 0
>>> x = 2
>>> p()
2 0
>>> y = 3
>>> p()
2 3
A partial function does something different. When you build a partial function, any variables passed to the constructor are evaluated, and the value is passed to the constructor (just like any Python function call).Output:Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import partial
>>> x = 0
>>> y = 1
>>> p = partial(print, x, y)
>>> p()
0 1
>>> x = 10
>>> y = 42
>>> p()
0 1
>>>
The partial never knew about x or y. The partial() constructor was passed 0 and 1, not x and y.