Modules. General concepts. Creating a module. Statements import, from
Contents
- 1. The concept of the module. Structuring programs using modules. Module attributes. Module import
- 2. The need to use modules
- 3. Organization of applications in Python. The main file of the program in modular construction. Secondary files
- 4. An example of organizing a program consisting of three files. Figure
- 5. Creating a module using Python
- 6. Ways to include content from other modules
- 7. Access to entire module. The import statement
- 8. Access to individual module components. The from-import statement
- 9. Access to module names. Instruction from*
- Related topics
Search other resources:
1. The concept of the module. Structuring programs using modules. Module attributes. Module import
When writing large programs or when the size of the program increases, the need for a correct (correct) partitioning of the program into structurally independent parts becomes more and more.
The purpose of this structuring is:
- facilitating the writing or development of the program;
- improvement of program support;
- reducing the number of logical errors, and consequently improving the quality of program development.
To provide structuring in the Python language, so-called modules are used. A module is a program unit that contains program code and data and is designed to organize interaction between structurally independent (structurally unique) parts of the program. Each module has a corresponding program file. Conversely, each file is a separate module.
Any single module can be imported (connected, used) by another module. Also, a module can import (use) another module.
Components implemented in a module are called attributes. Components are names of variables associated with functions, objects, classes, etc.
There is also the concept of importing a module. Importing a module is connecting a module using special instructions in order to gain access to the software (tools) of this module. After import, the module attributes become available for use.
⇑
2. The need to use modules
The use of modules allows you to structure software components into self-contained packages called namespaces. As with any namespace when importing a module, all names are attributes of the imported module object. These names are declared in the global scope of the imported module.
The use of modules is important for the following reasons:
- code reuse. Each module is presented as a file. This allows you to connect its code in different (several) client parts of the program. A set of names or, in other words, a set of attributes of this module is formed in the module;
- distribution of namespaces. Modules are a natural way of grouping the components of a software system. With modules, names are isolated to avoid conflicts and naming confusion. The names used in modules are grouped according to some criteria. Objects and programming code are implicitly included in modules;
- sharing of software components and data. Here we mean that the same module can be used in different components of the program system. There is only one module – there are several client program components.
⇑
3. Organization of applications in Python. The main file of the program in modular construction. Secondary files
As a rule, any modern Python program is built in such a way that it uses or consists of several files, also called modules. If an application is built so that it contains several modules, then this program has one main file. This file launches the entire program. This file usually includes other modules of the entire program. The main file defines the progress of the main thread. In turn, connected modules can use the tools of other modules to work.
If the main file will not be imported into other files, its extension can be anything (not necessarily *.py extension). It is important that this extension has all other modules included in this file. In any case, it is recommended to set the main file extension to *.py, since this extension makes the purpose of this file more obvious and will later allow it to be imported into other files.
Other or non-essential program files can also be executed if they are active in the Python editor window. If these files contain libraries of functions, then this property can be used to test these functions in the same module. After testing, it is important to remember to remove this code, since the execution code of each module is also executed when the code of the main module is started.
⇑
4. An example of organizing a program consisting of three files. Figure
Figure 1 shows an example of organizing a program consisting of three files:
- main.py – main program file. From the editor window of this file, the program is launched and secondary modules are connected;
- figures.py, strings.py – secondary program files imported into the main.py file. The figures.py file contains functions for determining the characteristics of known figures. The strings.py file contains string processing functions. These files do not run as secondary programs.
Figure 1. Scheme of connecting additional modules and their use
As you can see from Figure 1, the functions Circumference(), AreaCircle(), VolumeSphere() are declared in the figures.py module. The ReverseString() and GetCharCount() functions are also declared in the strings.py module. To access the functions of the figures.py and strings.py modules in the main.py module, the following imports occur
import figures, strings
After that, you can access module functions using the syntax
figures.Circumference() figures.AreaCircle() figures.VolumeSphere() strings.ReverseString() strings.GetCharCount()
In turn, in the figures.py module, the files of the math standard library are connected
import math
which contains mathematical functions and constants. The figures.py module uses a constant
math.pi
which returns the number π = 3.1415… .
The architecture of the program shown in Figure 1 can be represented as follows (Figure 2).
Figure 2. Modules. Architecture of a program containing 3 files
⇑
5. Creating a module using Python
In classic Python, a module is created by calling the standard command to create a *.py file. One possible call is:
File -> New File
or the key combination Ctrl+N as shown in Figure 3.
Figure 3. Creating a new module in Python 3.0
As a result, a file named Untitled.py will be created, which should later be saved to permanent media (hard drive or other media) with a simultaneous indication of its name. This name will identify the module in other modules that will use it.
In various programming systems that support the Python language, the sequence of commands for creating a module is the same or similar.
⇑
6. Ways to include content from other modules
Connecting a module (file with *.py extension) is done using the following instructions:
- import – the whole module is included here;
- from – a separate component of the module is included here;
- from* – all names of the specified module are included here.
All three methods are discussed in more detail below.
⇑
7. Access an entire module. The import statement
To access another module completely, use the import statement, the call of which looks like:
import ModuleName
here
- ModuleName—name of the module. This is a *.py file. In this case, the ModuleName.py file is included. The file describes the program code with the data to be used in the current module. The name of the ModuleName.py file is replaced with the variable name ModuleName. The corresponding components (constituents) of this file are attributes of the ModuleName variable.
After connecting with the import directive, accessing an element from this module looks something like this
ModuleName.ItemName
here
- ItemName – element name from the ModuleName module. This element can be, for example, a function name, a global variable, a class name, and so on.
When splitting a program into modules, it is recommended to create module files in the default home directory. However, if you need to use module files from different directories and different media, then for this you need to enter the necessary directories in the PYTHONPATH variable. Setting the PYTHONPATH variable is out of the scope of this topic.
Example.
Suppose two modules have been created in the Python editor, named module01.py and module02.py. These modules are located in the same folder (directory).
The module02.py module implements a function for determining the characteristics of known geometric figures:
- Circumference() – the length of a circle;
- AreaCircle() – the area of a circle;
- VolumeSphere() – the volume of a sphere.
The text of the module02.py module
# Module module02.py # Functions for calculating the characteristics of known figures are declared here. # Include the math module in order to use the math.pi constant # and the math.pow() function import math # Function for calculating the circumference of a circle def Circumference(r): return 2*math.pi*r # Function for calculating the area of a circle def AreaCircle(r): return path.pi*r*r # Function for calculating the volume of a sphere def VolumeSphere(r): return 4.0/3.0 * math.pi*r*r*r
To use these functions in the module01.py module, you need to include module02.py using the statement
import module02.py
The demo text of the module01.py module is as follows
# Module module01.py # Include module02.py import module02 # Using module02.py module functions # 1. Calculate circumference print("Circumference(2.0) = ", module02.Circumference(2.0)) # 2. Calculate the area of a circle print("AreaCircle(2.0) = ", module02.AreaCircle(2.0)) # 3. Calculate the volume of a sphere print("VolumeSphere(2.0) = ", module02.VolumeSphere(2.0))
After running the module01.py module, the program will display the following result
Circumference(2.0) = 12.566370614359172 AreaCircle(2.0) = 12.566370614359172 VolumeSphere(2.0) = 33.510321638291124
⇑
8. Access to individual module components. The from-import statement
In Python, it is possible to gain simplified access to the elements of a module using the from-import statement. In general, the use of this instruction is as follows:
from ModuleName import ItemName
here
- ModuleName – name of the module whose elements are to be accessed;
- ItemName – module element name. A module element can be a class, a function, a global constant, and so on.
After such a connection, you can access the ItemName element without specifying the ModuleName and the ‘ . ‘ (dot).
Example.
To get shorthand access to the sin() function from the math library, you need to use the following instruction
from math import sin
After that, you can call the sin() function without specifying the name of the math module
y = sin(0.5) # get sine of 0.5 radians
⇑
9. Access to module names. Instruction from*
The from statement has the special form from*. This form allows you to copy module names to the current module so that the module name does not need to be used when referring to its component. This reduces keyboard input and improves the readability of the program.
Example.
The example imports names from the random module. This module contains functions for generating random numbers. For demonstration purposes, the randrange() function is called, which generates an integer in the given range. Based on the randrange() call, a list of 10 integers is formed.
# Import all components from random module from random import * # Generate a list of random integers, # each of which is in range [0; twenty] # 1. Form an empty list L = [] # 2. Loop of list L formation i = 1 while i<=10: # Invoke function from the random module num = randrange(0, 20) # Add number to the list L = L + [num] # Increase the counter i = i+1 # 3. Display the result print("L = ", L)
Result
L = [3, 18, 0, 19, 16, 10, 14, 0, 4, 14]
⇑
Related topics
⇑