Python Closer Grammar Questions.

Asked 2 years ago, Updated 2 years ago, 91 views

I'm confused whether the closure means an external function or an internal function.

And grammatically, it is explained that the internal function remembers the variables of the external function even after the end of the external function.

So in the case of Closer, is it an exception to the principle that the variables in the function disappear from memory after the function ends? In other words, I wonder if the variable of the external function used by the internal function does not disappear from memory and remains alive even when the external function is terminated.

python clojure

2022-09-22 19:09

1 Answers

By default, if you have an internal function, you can refer to it as a closure.

We're capturing variables on the external function side, and we're probably asking this.

In addition, Python is an environment with gc and memory cannot be cleaned up immediately after the function is terminated. It's solely up to the gc mechanism and this may vary from version to version of Python.

To understand how Python's closure deals with variables, you need to understand __close__.

def outer():
    v1, v2, v3 = 1, 2, 3
    def inner():
        s = v1 + v2 + v3 # Captured in the internal function by using the v1, v2, and v3 variables.
        pass
    return inner
innerF = outer()
innerF()

The innerF.__close__ # __close__ field is a tuple that stores the captured variable
(<cell at 0x7ff5d6ba5228: int object at 0x7ff6202494e0>,
 <cell at 0x7ff5d6ba5978: int object at 0x7ff620249500>,
 <cell at 0x7ff5d6ba5e28: int object at 0x7ff620249520>)

For vinnerF.__close__: # Output values stored in the __close__ field
    print(v.cell_contents)
1
2
3

I'll go one step further...Let's look at when we don't use variables from external functions.

def outer():
    v1, v2, v3 = 1, 2, 3
    def inner():
        #s = v1 + v2 + v3 #Annotation Processing
        pass
    return inner
innerF = outer()
innerF()

innerF.__close_ # No results

for v in innerF.__closure__:
    print(v.cell_contents)

TypeError: 'NoneType' object is not iterable

If you do not use the variable of the external function in the closeer, that is, the internal function, you can know it at the time of compilation (whether to keep it or not), and do not save it in __close__code>.

Rather than referring to the variables in the external function, you can understand that they are copied to the internal function (__close__) and stored.


2022-09-22 19:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.