Module in Python

In this Python lesson we will know how to create and import a module in Python. We will learn a few ways to import, using custom modules as well as Python's built-in modules, please watch.

In this Python lesson we will know how to create and import a module in Python. We will learn a few ways to import, using custom modules as well as Python's built-in modules, please watch.

What is the module in Python?

Module (module) refers to a file containing Python commands and definitions. A file contains Python code, for example quantrimangcom.py called module and the name of the module will be quantrimangcom.

Modules are often used when you want to split large programs into smaller files for easier management and organization. The most common are Python functions that must be used to be defined in a module and enter Python instead of copying the definitions in different programs. Thus, the module allows for code reuse.

Now try to create a module by entering the following code into the file and saving it with the name quantrimangcom.py.

 #Ví dụ về module Python 

def them(p, q):
"""Module này thêm 2 số
và trả về kết quả
by TipsMake.com"""


ket_qua = p + q
return ket_qua

Here, we define the extra function () in the module quantrimangcom. The function takes two numbers and returns their sum.

How to import modules in Python?

We can import definitions from this module into another module or into the interpreter in Python. We use the import keyword to do this. To import a defined module, we enter the following command at the Python prompt.

 >>> import quantrimangcom 

This command does not enter the name of the function defined in quantrimang.com directly in the current table, it only enters the name of the module. Use the module name to access the function with the operator (.). For example:

 >>> quantrimangcom.them (4.5.5.5) 
10.0

Make sure you have typed the correct module name, function name (case sensitive) if you receive the following message: "ModuleNotFoundError: No module named ."

Python already has many standard modules available. You can check the full list at: https://docs.python.org/3/py-modindex.html . Here, you can see the module name, what their task is. These files are available in Lib in the directory where you install Python. These modules can be entered similar to the way we enter the self-defined module.

There are many ways to import modules as follows:

Use the import command

We can use the import command to import the module and access the definitions within it, using the operator. as described above. Here is an example:

 # Import command to import modules is available in Python 
# TipsMake.com
import math
print ("The value of pi is:", math.pi)

When running Python code above we get the result:

 The value of pi is: 3.141592653589793 

Enter the module and edit the name when entering

 # Enter the module and edit its name 
# TipsMake.com
import math as m
print ("The value of pi is:", m.pi)

We have renamed the math module to m, which can save time in some cases. Note, this rename applies only to the command scope, not actually renaming the module in Lib. When you rename, you must type the correct module name, the math is not recognized at the command range anymore, but you must use m to correct.

From . import command in Python

We can enter a specific name from the module without entering the entire module as the example below:

 # Enter pi only from math module 
# TipsMake.com
from math import pi
print ("The value of pi is:", pi)

The above code only imports pi from the math module. In this case there is no need to use the "." Operator. We can enter many properties of the module as shown below:

 # Enter multiple properties from math module 
# TipsMake.com
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

Enter all names

We can enter all names (definitions) from a module using the following code:

 # Enter all names from the math module 
# TipsMake.com
form math import *
print ("The value of pi is:", pi)

We enter all the definitions from the math module so all names are visible within this range, except for names starting with underscores _.

Entering everything with an asterisk * is not a good programming habit. Because it can lead to duplicate definitions for the same identifier and make reading code more difficult.

Path to search Python modules

When entering the module, Python will find a few places. The interpreter finds available modules, if not, it will list the directories defined in sys.path. The search order will be:

  1. Current directory.
  2. PYTHONPATH (an environment variable with directory listing).
  3. The default directory is located depending on the selection during installation.

Enter the following commands in turn to see the link:

 >>> import sys 
>>> sys.path

We can edit this list to add custom paths as desired.

Reload the module

The Python interpreter only imports one module in a session. This makes everything more efficient. Here is an example to illustrate how this works.

You write the following code in the new file, named module_1 :

 print ("Code already active") 

Now try entering module module_1 to see the effect of entering the module many times.

 >>> import module_1 
Code already active
>>> import module_1
>>> import module_1
>>> import module_1
>>>

You can see that the above code only works once, meaning that module_1 is only entered once in that session. Now if you modify the code in module_1 you have to reload it. To do this you have to restart the interpreter, but this may not look very good.

Python provides a smarter way to do this. You can use the reload() function in the imp module to reload module_1 , as shown below:

 >>> import module_1 
Code already active
>>> import module_1
>>> import module_1
>>> import module_1
>>> import imp
>>> imp.reload (module_1)
Code already active

The function dir () in Python

The function dir () in Python is used to find the names defined in a module. For example, you define the extra function () in the original example.

You enter the following commands in turn:

 >>> import Quantrimangcom 
>>> dir (Quantrimangcom)

And the results returned:

 ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'them'] 
>>>

The output is a list of names defined in the module, arranged in order (along with them ). All names starting with underscores are the default Python attributes, linked to the module. For example, __name__ contains the module name.

 >>> import Quantrimangcom 
>>> Quantrimangcom .__ name__
'Quantrimangcom'
>>>

All names defined in namespaces can be found using dir () without any parameters.

 >>> a = 10 
>>> b = 15
>>> quantrimangcom = 20
>>> import math
>>> dir ()
['Quantrimangcom', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'math', ' quantrimangcom ',' them ',' vidu ']
>>>

This module post is temporarily finished, so don't forget to do Python exercises.

Next lesson: Package in Python

Previous article: Global keyword in Python

See more:

  1. Recursive function in Python
  2. Anonymous function, Lambda in Python
  3. Variable types in Python
5 ★ | 1 Vote