Python Basics: Scope and Namespaces

A namespace is where variables are stored, while a scope is the scope in which variables are valid.

  • Scope (Scope) refers to the effective range of variables. There are three types of scope in Python:
    • Local scope refers to the scope inside the function;
    • The global scope refers to the scope outside all functions in the program;
    • Built-in scope refers to the scope built into the Python interpreter.
  • Namespace refers to the location where variables are stored. Variables in Python are stored in different namespaces:
    • Local Scope: The local namespace, which contains the variables and function names defined inside the function;
    • Enclosing Scope: The namespace of the external nested function, including the variable and function names defined in the nested function;
    • Global Scope: the global namespace, including the variable and function names defined in the module;
    • Built-in Scope: The built-in namespace contains the function and variable names built into the Python interpreter.

To put it simply, in a function func(), its local namespace is func, and the internally defined attributes or methods are all in this namespace, and its valid scope (scope and scope) is inside the function.

In order to assist the explanation later, the following introduces several built-in functions of python

  • locals() Used to view variables in the namespace of the current scope. It returns a dictionary whose keys are the variable names and whose values ​​are the values ​​of the variables. Can only be used inside a function.
  • globals() Used to view variables in the namespace of the global scope. It returns a dictionary whose keys are the variable names and whose values ​​are the values ​​of the variables. Can be used anywhere.
  • dir( object ) If no arguments, returns a list of names in the current local scope. If given an argument, it attempts to return a list of valid properties for the object. If the object has a  __dir__() method named , then that method will be called and must return a property list.

The following is a brief explanation of the usage

a = 1
print('globals:', globals())
print('dir:', dir())

 The output is:

globals: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000013C08576CD0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:\\project\\python100days\\1.py', '__cached__': None, 'a': 1}
dir: ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a']

You can see that the list returned by dir() is the variable name of all attributes, while globals() returns a dictionary, including the previous variable name and the value of each variable

Next, let's look at examples of namespaces and scopes:

a = 1
def foo():
    b = 2
    print("foo内部的局部命名空间:", locals())
    print("foo内部的全局命名空间:", globals())
    print('foo内部的当前命名空间(应为当前局部命名空间):', dir())

foo()
print('foo外部的全局命名空间:', globals())
print('foo外部的当前命名空间(应为全局命名空间):', dir())
print('全局命名空间中’foo‘的命名空间:', dir(foo))

output:

foo内部的局部命名空间: {'b': 2}
foo内部的全局命名空间: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002C6C3346CD0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:\\project\\python100days\\1.py', '__cached__': None, 'a': 1, 'foo': <function foo at 0x000002C6C338F160>}
foo内部的当前命名空间(应为当前局部命名空间): ['b']
foo外部的全局命名空间: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002C6C3346CD0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:\\project\\python100days\\1.py', '__cached__': None, 'a': 1, 'foo': <function foo at 0x000002C6C338F160>}
foo外部的当前命名空间(应为全局命名空间): ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'foo']
全局命名空间中’foo‘的命名空间: ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

 

It can be seen here:
1. The global namespace is the same inside and outside foo;
2. When inside foo, dir outputs the current namespace as the local namespace; when outside foo, dir outputs the current namespace as the global namespace Namespaces.
3. When dir(foo), output the name list of the properties and methods of the function object, including the built-in properties and methods of the function, as well as the special methods available to the function object. (ps: For a function object, some of the attributes and methods are automatically added by the Python interpreter, such as the __call__ method, which defines how the function object is called)

 

Guess you like

Origin blog.csdn.net/qq_36497369/article/details/130128616