Importing a module. Sequence of actions: search-compilation-run. The sys.path list. Scheme of actions performed
This topic is a continuation of the topic:
- 1. The sequence of actions when performing an import
- 2. Module search. The sys.path attribute
- 3. Using the modules of the Python standard library. Example
- 4. Compilation. Getting the bytecode of the module (*.pyc). Scheme of actions performed
- 5. Run module bytecode
- Related topics
Search other resources:
1. The sequence of actions when performing an import
The import of a module is done only once. If you call the module import command again, it will be ignored. The first time another module is imported, the following run-time operations are performed:
- Find the module file.
- The detected file is compiled into bytecode if necessary.
- The program code of the module is launched. As a result, the objects defined in this module are created.
2. Module search. The sys.path attribute
When performing an import, the first operation performed by the interpreter is to find the location of the module file. The *.py extension is not specified in the import statement, only the module name is specified. Also, the path to the directory containing the module file is not specified.
When writing programs built using modules, in most cases you do not need to set the path to the directories with the modules used. It is enough to use the automatically configured module search paths if you place the files of these modules in the same directory as the main file (executable file).
If the program uses modules of other (third-party) developers structured in directories, then it may be necessary to configure these custom directories.
The path attribute of the sys module is used to set the directory names to be used in the program. The sys module is part of the standard library. Directory names are specified as a list of strings.
Figure 1. Viewing the contents of the sys.path file with the File->Path Browser command
When importing a module, the important thing is how you find the correct directory. The directories that come first in the list are considered first. In any case, the search for the required module is carried out from the following basic sources describing directories, in the following sequence:
- The current (home) directory of the program. This component is detected automatically.
- Using the PYTHONPATH environment variable (if one is defined). This variable defines a list of directory names with a list of modules defined by the user and the system. If the PYTHONPATH variable is defined, then the interpreter uses this variable to find the paths to the modules used. This is the case when the programmer (user) needs to import modules that are structured in directories (located in different directories).
- Using the catalogs of the standard library (see item 3). After completing steps 1, 2, the connected modules are searched in the directories of the standard library. These directories are automatically included by the interpreter, so there is no need to set them up manually.
- Using the *.pth file. In this text file, the desired directories are specified using a list of strings.
Figure 2. Sequence of sources when searching for a module in the sys.path list
3. Using the modules of the Python standard library. Example
When creating a program in Python, about 200 modules of the standard library are available to the programmer. Access to these modules is carried out in the usual way using the import, from statements. The standard library modules can be used on any platform that runs a Python interpreter.
The Python Standard Library modules provide tools for solving the most common programming tasks. Such tools include:
- the relationship (interface) of the program with the operating system;
- implementation of different types of object storages;
- organization of network communication;
- implementation of known patterns;
- organization of the graphical user interface;
- mathematical tools;
- tools of various types of processing of numerical information;
- libraries of ready-made solutions for visualization of changing processes in space;
- other tools.
The example shows the use of the math and random libraries. Initially, a list of pairs of random numbers is formed using the random module. These pairs represent the coordinates of points on the plane. Then, using the sqrt() function of the math module, a list of distances from each point to the origin is obtained.
# 1. Include standard random and math modules import random, math # 2. Create a list of pairs of random numbers. # Each pair is a tuple that defines the (x; y) coordinates of a point on the plane # 2.1. Set the number of points n = input("n = ") # 2.2. Cycle of formation of the list of points i = 0 L =  # resulting string while i < n: # 2.2.1. Form coordinates x, y # Use the standard Function from the random module x = random.randint(-10, 10) # x = [-10; 10] y = random.randint(-10, 10) # y = [-10; 10] # 2.2.2. Add point to list L L = L + [(x, y)] # 2.2.3. Increment the iteration counter of the loop by 1 i = i+1 # 3. Display the list print("L = ", L) # 4. Generate a list of distances from points to the origin L2 =  # List of distances for pt in L: # Вычислить расстояние от точки pt до начала координат length = math.sqrt(pt*pt+pt*pt) # Add distance to list L2 L2 = L2 + [length] # 5. Print a list of distances with 2 decimal places of precision s = "" # Resulting string for l in L2: s = s + ("%.2f" % (l)) + " " print("L2 = ", s)
n = 6 L = [(5, 3), (-7, 9), (-8, -9), (6, -2), (-3, -6), (0, 5)] L2 = '5.83 11.40 12.04 6.32 6.71 5.00 '
4. Compilation. Getting the bytecode of the module (*.pyc). Scheme of actions performed
After searching for the module specified in the import statement, the next stage occurs – the compilation stage. At this point, the interpreter compiles the module file into bytecode, if needed. The bytecode file has *.pyc extension.
The interpreter does the following:
- fixes the creation time of the module file (extension *.py);
- determines the creation time of the bytecode file (extension *.pyc);
- if the creation time of the bytecode file (*.pyc) is not older than the module file (*.py), then the compilation step is skipped;
- if the bytecode file is present but the module file is missing, the compiler will load the bytecode. This means that you can distribute your own program as bytecode and thus hide the source code of the program. In this case, the compilation step is skipped;
- if changes are made to the source file of the module, then the next time the program is started, a new bytecode from this module will be generated.
Figure 3 shows a diagram of the actions performed by the interpreter using the example of two files main.py and myLib.py. Gets bytecode from myLib.py module if needed
Figure 3. The scheme for performing actions by the interpreter when a file is included with the import statement
5. Run module bytecode
Running the module bytecode is the last step in the import operation. Before the launch, the bytecode of the module has already been generated, placed in a file with the *.pyc extension. The instructions contained in a module are executed one after the other in a top-down fashion. An object is created for the module. The attributes of this object are created when any assignment (=) operation is performed.