What exactly is a Python Module?
Python modules are files that contain Python definitions and statements. Functions, classes, and variables can all be defined by a module. A module may also contain executable code. Grouping related code into modules makes it easier to understand and use the code. It also helps to organize the code logically.
Importing Modules in Python:
Using the import statement in another Python source file, we can import the functions and classes defined in one module into another.
When the interpreter comes across an import statement, it imports the module if it is in the search path. A search path is a directory list that the interpreter looks through when importing a module. To import the module calc.py, for example, place the following command at the top of the script.
Creating a simple module:
# A simple module, cal.py def mul(x, y): return (x*y) def div(x, y): return (x/y)
Importing the cal.py module:
# importing module cal.py import calc print(calc.mul(10, 2))
Import all Names:
The import statement’s * symbol is used to import all the names from a module into the current namespace.
from math import * # if we simply do "import math", then # math.sqrt(16) and math.factorial() # are required. print(sqrt(16)) print(factorial(6))
Locating Python Modules:
When a module is imported into Python, the interpreter looks in several places. It will first look for the built-in module, and if it is not found, it will look for a list of directories defined in the sys.path. The Python interpreter looks for the module in the following way:
- It begins by looking for the module in the current directory.
- If the module is not found in the current directory, Python searches the shell variable PYTHONPATH. PYTHONPATH is an environment variable that contains a list of directories.
- If that fails as well, Python checks the installation-dependent list of directories that was configured when Python was installed.
Note: also read about Python Variables
Please follow me to read my latest post on programming and technology if you like my post.
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.