We create our own module in the same way as a regular program, and save with the same extension. So that the program can be used as module, we need to write functions that we can then use in others programs.
It is better to place the module file in the folder with the program being created, since Python, when connecting a module, first looks for it in the current directory.
Let's say we need a module to perform geometric calculations. In it We will have 2 functions. One for calculating the area of a triangle, the other for calculating the area of a circle.
Let's create a file and save it under the name mygeometry.py
We implement 2 functions in it:
area of a circle
To simplify the example, we will not perform an existence check triangle along the entered sides.
Code: modules - file mygeometry.py
import math
def striangle(a, b, c):
p = (a + b + c) / 2
s = math.sqrt(p * (p - a) * (p - b) * (p - c))
return s
def scircle(r):
s = math.pi * r * r
return s
Please note that in this module we first include the math module, we need it needed to extract the square root and obtain the number π.
Now let's create a second file file.py in which we will use our created module.
The help() function will display all the information about the module: where it is located, and what functions are implemented in it. Let's run the file to calculate the area of the triangle.
Code: modules - file.py
import mygeometry
print(help('mygeometry'))
a = int(input('a= '))
b = int(input('b= '))
c = int(input('c= '))
r = int(input('r= '))
print(f'Triangle s= {mygeometry.striangle(a, b, c):.1f}')
print(f'Circle s= {mygeometry.scircle(r):.1f}')
'''
Help on module mygeometry:
NAME
mygeometry
FUNCTIONS
scircle(r)
striangle(a, b, c)
FILE
f:\user\math\mygeometry.py
None
a= 2
b= 2
c= 3
r= 4
Triangle s= 2.0
Circle s= 50.3
'''
If you need to place the module in a different location, then you need to point to it path in sys.path. For example, we created a module mygeometry.py and placed it in the folder C:\user\math\modules, and the program that uses this module was saved in a different directory. Then the module must be connected as follows:
Code: modules - file.py
import sys
import os
print("OS operating systems: ", sys.platform)
print("Sys version: ", sys.version)
print("Path sep: ", os.pathsep)
print("OS sep: ", os.sep)
''' Windows operating systems (OS) '''
# print(sys.path.append(r"C:\user\math\modules"))
'''
Cross-platform operating systems (OS)
Windows, macOS, and Linux
'''
absolute_path = os.path.dirname(__file__) + os.sep + "modules"
print(absolute_path)
print(sys.path.append(absolute_path))
import mygeometry
print(help('mygeometry'))
a = int(input('a= '))
b = int(input('b= '))
c = int(input('c= '))
r = int(input('r= '))
print(f'Triangle s= {mygeometry.striangle(a, b, c):.1f}')
print(f'Circle s= {mygeometry.scircle(r):.1f}')
'''
Output:
OS operating systems: win32
Sys version: 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)]
Path sep: ;
OS sep: \
C:\user\math\modules
None
Help on module mygeometry:
NAME
mygeometry
FUNCTIONS
scircle(r)
striangle(a, b, c)
FILE
C:\user\math\modules\mygeometry.py
None
a= 2
b= 2
c= 3
r= 4
Triangle s= 2.0
Circle s= 50.3
'''
When we import a module like mygeometry in Python, a folder named __pycache__ might be created. This folder is used for storing compiled bytecode versions of your modules to speed up import times. It contains optimized versions of your Python files, which are platform-independent. This bytecode compilation happens by default in Python 3 whenever you import a module, though you can disable it if necessary. The purpose of this is to avoid recompiling the source code each time it's imported, thus improving performance.
A Python module can be any source code file in this language. Each Python file can be run as a separate program or can be imported as a module into another executable program. If the imported file was originally created as a "classic" module, containing only a set of different functions, then the functions are executed only when called. However, if the imported file is a program containing both regular instructions and functions, then at the point where the module is imported, the execution of the program stops and does not resume until the code from the imported file is executed. Therefore, there is a need to separate the code that should be executed when the file is run as a standalone program from the code that should be executed when using the file as a module.
Every file in Python has a special attribute called __name__, the value of which is set to 'main' if the file is executed as the main program and not imported as a module. By checking if the attribute __name__ is equal to 'main', you can determine whether the file is the main executed program or an imported module.
Let's consider two simple files.
The first file: m1.py
Code: file m1.py
print('Module 1 started')
print('Connect module 2')
import m2
print('Last instruction of module 1')
The second file: m2.py
Code: file m2.py
print('Module 2 started')
if __name__ == '__main__':
print('Module 2 started as main program')
print('Last instruction of module 2')
If you run the m2.py file, the following result will be displayed:
Code: run file m2.py
Module 2 started
Module 2 started as main program
Last instruction of module 2
If you run the m1.py file, the following result will be displayed:
Code: run file m1.py
Module 1 started
Connect module 2
Module 2 started
Last instruction of module 2
Last instruction of module 1
Please note that in the second case (run file m1.py) the line 'Module 2 started as main program' was not displayed as the main program." This suggests that in the second case the file m2.py launched as a module inside the m1.py file.