Python namespaces and closures

1. Namespace (namespace)
1. Classification
of namespaces In Python, the identification of functions/methods, variables and other information with the same name is realized by providing namespaces. There are three kinds of namespaces, namely:,
    - local namespace: The scope of action is The current function or class method
    - global namespace: the scope is the current module
    - build-in namespace: the scope is all modules

2. Namespace search order
    1. local namespace
    2. global namespace
    3. build-in namespace

3. Scope
Global scope: Built-in namespace, global namespace
Local scope: Local namespace
Variables in global scope: Globally valid, can be accessed anywhere, unless del is deleted, it will survive until the file is executed .
Local scope Domain variables: locally valid, can only be called in the local scope, only valid when the function is called, and invalid when the call ends
```
x=1000
def func(y):
        x=2
        print(locals()) # {' x': 2, 'y': 1} local namespace variables, used in this function
        print(globals())              
        # Global namespace variables: {'__package__': None, 'x': 1000, '__file__': '...', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x008059B0>, '__doc__': None, '__name__ ': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'func': <function func at 0x0136D7C8>, '__spec__': None, '__cached__': None}
#
func(1)
print(locals())
print(globals())
print(globals() is locals()) # True
# locals is in the global space outside the function, so it is the same as globals()
```

Second, closure (closure)
1. Create a poster
Creating a closure in Python can be boiled down to the following three points:
    - The closure function must have an embedded function
    - The embedded function needs to refer to a variable in the namespace one level above the nested function
    - The closure function must return Inline function


2.Example
```
x=1
y=2
def f1():
        x=1
        def f2():
            print(x,y)
        return f2
f=f1()
print(dir(f)) # It can be seen from the result that the f object contains the __closure__ attribute
print(f.__closure__) # __closure__ corresponding tuple , contains an object of cell type
print(f.__closure__[0]) # object of cell type
print(f.__closure__[0].cell_contents) # cell value
-------------- -------------------------------------------------- -------------------
Result:
4 2
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
(<cell at 0x014659D0: int object at 0x1D468A00>,)
<cell at 0x014659D0:int object at 0x1D468A00> The principle of conclusion closure, when the embedded function references the variables in the enclosing function (enclosing function), these variables will be saved in the __closure__ attribute of the enclosing function , become part of the enclosing function itself; that is, these variables will have the same lifetime as the enclosing function.3.````
4



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324941212&siteId=291194637