An object is destroyed only when it ceases to be needed by someone else; in CPython
this happens when the number of references to an object becomes zero.
v
in this example, a closure that has access to both its names (in this example, they are not available), and to the names inside the function aaa
(ie, t
, bbb
), other more external functions (also not) to the global names relative to the place in which the function was declared (i.e. aaa
, v
)
A closure is a function that captures the variables of its originating function, or functions even higher in the hierarchy, and has the ability to work with them, even if that function has already completed.
Examples:
def aaa(x): def bbb(y): def ccc(z): return x + y * z return ccc return bbb print(aaa(5)(6)(7)) # 47
def message(secret): def helper(): return f'Никто кроме меня не знает, что secret={secret!r}' return helper f1 = message("password") f2 = message("hack the internet") print(f1()) # Никто кроме меня не знает, что secret='password' print(f2()) # Никто кроме меня не знает, что secret='hack the internet'
def notinlist(lst): def helper(x): return x not in lst return helper print(*filter(notinlist([1,3]), range(10))) # 0 2 4 5 6 7 8 9
And all the same, but with the help of anonymous "lambda" functions
def aaa(x): return lambda y: lambda z: x + y * z
def notinlist(lst): return lambda x: x not in lst
def message(secret): return lambda: f'Никто кроме меня не знает, что secret={secret!r}'
def bbb()
function you automatically created a closure and then placed this function in the variablev
, so that both the function and the closure and the variablet
in this closure were successfully saved - andreymalt
can be detected stored inv.__closure__[0].cell_contents
- andreymalt
in this namespace - this is the essence of the closure - andreymal 5:09