A python module is a file containing Python definitions and statements. A module can define functions, classes and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized. 

Import Modules in Python

We cab import the functions, and classes defined in a module to another module using the import statements in some other python source file.

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module. For example, to import the module calc.py. we need to put the following command at the top of the script.

The form – import Statement in Python 

Python’s from statement lets you import specific attributes a module without importing the module as a whole.

Import all Names

The * symbol used with the from import statement is used to import all the names from a module to a current namespace.

From import * Statement

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module, it is not recommended to use *, else do so.

Locating Python Modules  

Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for the built in module if not found then it looks for a list directories defined the sys.path. Python interpreter searches for the module in the following manner 

First, it searches for the module in the current directory.

If the module is’nt found in the current directory. Python then searches each directory in the shell variable , consisting  of a list of directories.

if that also fails python checks the installation – dependent list of directories configured at the time python is installed.

Recent Comments
Scroll to Top