In Python, the concepts of module, scope, and namespace are closely related to the operating mechanism of virtual machines.
Here we first understand module, scope, and namespace, and prepare for the subsequent analysis of the virtual machine's operation.
Module
In Python, a file corresponds to a module, and each py file is imported with a Module object.
This object contains a Dict object that holds a reference to the corresponding variable and function in this py file.
A reference to a variable or function imported from another Python file (module) is also saved.
Name spaces and scopes
Python has three separate namespaces, local, global, builtin.
Builtin is the global namespace of the Python interpreter
Global is the universal namespace of the module object and holds references to variables and functions in the module
Local correspondence is the namespace of the current code block, saving local variables and function references
In a python file, each block of code corresponds to a scope and also to a name space.
When using variables or functions, look in the order of the name space Local,global,builtin.
Code blocks can be nested, so the local name space is also nested lookups.
Examples of scopes
#!/usr/bin/env python# coding:utf-8# test.py# global scope, define variable A, function Showa = ' Hello word ' def show (): # function Show local scope name = ' Show function ' Def myhelp (): # Local scope of function Myhelp # using global scope variable a print a # using the local scope of the show function Inside the variable name print name
Summarize
code block corresponds to scope and name space
namespace holds variables and function references in scope
Each code block corresponds to a Pycodeobject object of the PYc bytecode file (see ZG manual python2.7.7 Source Analysis (4)--PYc bytecode file)
Once you understand the above concepts, you can understand how the virtual machine works.
Original link: ZG manual python2.7.7 Source Analysis (5)--Python scope and name space
ZG manual python2.7.7 Source Code Analysis (5)--Python scope and name space