Table of Contents
This guide covers module in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
Module (module) refers to a file containing Python commands and definitions. A file contains Python code, for example tipsmakecom. Py called module and the name of the module will be tipsmakecom.
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 tipsmakecom. Py.
#Ví dụ về module Pythondef them(p, q):"""Module này thêm 2 sốvà trả về kết quảby TipsMake.com"""ket_qua = p + qreturn ket_qua
Here, we define the extra function () in the module tipsmakecom. The function takes two numbers and returns their sum.
You can import definitions from this module into another module or into the interpreter in Python. We use theimportKeyword to do this. To import a defined module, we enter the following command at the Python prompt.
>>> import tipsmakecom
This command does not enter the name of the function defined intipsmake.comDirectly 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:
>>> tipsmakecom.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:
How to Use the Import Command
You 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
You 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
You 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:
- Current directory.
- PYTHONPATH (an environment variable with directory listing).
- 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
You 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, namedmodule_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 thatmodule_1Is only entered once in that session. Now if you modify the code inmodule_1You 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 thereload()Function in the imp module to reloadmodule_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 Tipsmakecom >>> dir (Tipsmakecom)
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 withthem). All names starting with underscores are the default Python attributes, linked to the module. For example,__name__Contains the module name.
>>> import Tipsmakecom >>> Tipsmakecom .__ name__ 'Tipsmakecom' >>>
All names defined in namespaces can be found using dir () without any parameters.
>>> a = 10 >>> b = 15 >>> tipsmakecom = 20 >>> import math >>> dir () ['Tipsmakecom', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'math', ' tipsmakecom ',' 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
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.