Home Backend Development Python Tutorial Python namespace instance parsing

Python namespace instance parsing

Oct 19, 2016 pm 05:19 PM
python

Python’s namespace is something that Python programmers must understand. Learning about Python’s namespace will enable us to essentially master some trivial rules in Python.

Next, I will reveal the essence of Python namespaces in four parts: 1. The definition of namespaces; 2. The search order of namespaces; 3. The life cycle of namespaces; 4. BIF through locals() and globals() Accessing namespaces

The focus is on the fourth part, where we will observe the contents of namespaces.

1. Namespace

Python uses something called a namespace to record the trajectory of variables. A namespace is a dictionary whose keys are variable names and whose values ​​are the values ​​of those variables.

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries.


Anywhere in a Python program, there are several available namespaces.

1. Each function has its own namespace, called the local namespace, which records the variables of the function, including function parameters and locally defined variables.

2. Each module has its own namespace, called the global namespace, which records the variables of the module, including functions, classes, other imported modules, module-level variables and constants.

3. There is also a built-in namespace, which can be accessed by any module and stores built-in functions and exceptions.


2. Namespace search order

When a line of code wants to use the value of variable x, Python will search for the variable in all available namespaces, in the following order:

1. Local namespace: specifically The current function or class method. If the function defines a local variable x, or a parameter x, Python will use it and then stop searching.

2. Global namespace: specifically refers to the current module. If the module defines a variable, function, or class named x, Python will use it and then stop searching.

3. Built-in namespace: global for each module. As a last resort, Python will assume that x is a built-in function or variable.

4. If Python cannot find x in these namespaces, it will give up the search and raise a NameError exception, such as NameError: name 'aa' is not defined.


The situation of nested functions:

1. First search

in the namespace of the current (nested or lambda) function 2. Then search in the namespace of the parent function

3. Then Search in the module namespace

4. Finally, search in the built-in namespace


Example:

info = "Adress : "
 def func_father(country):
     def func_son(area):
         city= "Shanghai " #此处的city变量,覆盖了父函数的city变量
         print(info + country + city + area)
     city = " Beijing "
     #调用内部函数
     func_son("ChaoYang ");
    
 func_father("China ")
Copy after login


Output: Adress: China Shanghai ChaoYang

In the above example, info is in the global In the namespace, country is in the namespace of the parent function, and city and area are in the namespace of its own function. There are different lifetimes.

1. The built-in namespace is created when the Python interpreter starts, and will always be retained and will not be deleted.

2. The global namespace of the module is created when the module definition is read in. Usually the module namespace will be saved until the interpreter exits.


3. A local namespace is created when the function is called, and is deleted when the function returns a result or throws an exception. Each recursively called function has its own namespace.

 One of the special things about Python is that its assignment operations are always in the innermost scope. Assignment does not copy the data - it just binds the name to the object. The same goes for deletion: "del y" simply deletes the name y from the local scope's namespace. In fact, all operations that introduce new names operate on the local scope.

Example:

i=1

def func2():


i=i+1

func2();

#Error: UnboundLocalError: local variable 'i' referenced before assignment

Due to When creating a namespace, python checks the code and populates the local namespace. Before Python runs that line of code, it finds the assignment to i and adds it to the local namespace. When the function executes, the python interpreter thinks that i is in the local namespace but has no value, so an error occurs.

def func3():


 y=123

 del y

 print(y)

func3()

#Error: UnboundLocalError: local variable 'y' referenced before assignment

#Remove "del y" After the statement, it runs normally

4. Namespace access

1. The local namespace can be accessed using locals() BIF.

locals returns a dictionary of name/value pairs. The keys of this dictionary are variable names in the form of strings, and the values ​​of the dictionary are the actual values ​​of the variables.

Example:


def func1(i, str):

x = 12345

print(locals())

func1(1, "first")

输出:{'str': 'first', 'x': 12345, 'i': 1}


2、全局 (模块级别)命名空间可以通过 globals() BIF来访问。

示例:

'''Created on 2013-5-26'''
   
import copy
from copy import deepcopy
   
gstr = "global string"
   
def func1(i, info):
    x = 12345
    print(locals())
   
func1(1 , "first")
   
if __name__ == "__main__":
    print("the current scope's global variables:")
    dictionary=globals()
    print(dictionary)
Copy after login


输出:(我自己给人为的换行、更换了顺序,加颜色的语句下面重点说明)

{

'__name__': '__main__',

'__doc__': 'Created on 2013-5-26',

'__package__': None,

'__cached__': None,

'__file__': 'E:\\WorkspaceP\\Test1\\src\\base\\test1.py',

'__loader__': <_frozen_importlib.SourceFileLoader object at 0x01C702D0>,

'copy': ,

'__builtins__': ,

'gstr': 'global string',

'dictionary': {...},

'func1': ,

'deepcopy':

}


总结

  1、模块的名字空间不仅仅包含模块级的变量和常量,还包括所有在模块中定义的函数和类。除此以外,它还包括了任何被导入到模块中的东西。

  2、我们看到,内置命名也同样被包含在一个模块中,它被称作 __builtin__。

  3、回想一下 from module import 和 import module 之间的不同。

    使用 import module,模块自身被导入,但是它保持着自已的名字空间,这就是为什么您需要使用模块名来访问它的函数或属性:module.function 的原因。

    但是使用 from module import function,实际上是从另一个模块中将指定的函数和属性导入到您自己的名字空间,这就是为什么您可以直接访问它们却不需要引用它们所来源的模块。使用 globals 函数,您会真切地看到这一切的发生,见上面的红色输出语句。


3、 locals 与 globals 之间的一个重要的区别

locals 是只读的,globals 不是

示例:

def func1(i, info):
    x = 12345
    print(locals())
    locals()["x"]= 6789
    print("x=",x)
   
y=54321
func1(1 , "first")
globals()["y"]= 9876
print( "y=",y)
Copy after login

   


输出:

{'i': 1, 'x': 12345, 'info': 'first'}

x= 12345

y= 9876

解释:

  locals 实际上没有返回局部名字空间,它返回的是一个拷贝。所以对它进行改变对局部名字空间中的变量值并无影响。

  globals 返回实际的全局名字空间,而不是一个拷贝。所以对 globals 所返回的 dictionary 的任何的改动都会直接影响到全局变量。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles