While learning python programming language we generally write some code or sample applications. But these will generally consist of few line of code below 100 lines. In real world applications situation is different. We generally write a lot of code, function, helpers etc. Generally these applications consist of above 10.000 lines of code. Putting all of these code into single or few
py files is not a practical or logical solution. Python provides modules to make things more modular and tidy. We can put codes into different files in a hierarchical manner.
Creating module is easy as creating a source file and putting some code into this source file. We will create a module named
mymodule.py with some code like below.
#Sum up given variables
Module Search Path
We have created module and put
/home/ismail directory in operating system files system. But how can we access this module from different directories for load operation. Python uses search path to locate modules named
PYTHONPATH . Python follows below step to search and load modules
- Look current working directory
PYTHONPATHenvironment variable provided directories
- Installation dependent default
As previously stated we can provide module directory different way. The most reliable way to set modules path is setting
PYTHONPATH environment variable. We will run this command in operating system shell . If we want to make
PYTHONPATH variable persistent we should add this to startup config .
This will add
/home/ismail/modules to the
PYTHONPATH in Linux systems.
We have previously created a module named
mymodule.py . We want to use the
sum function inside this module. So we should import this module. We will import module with
import directive by specifying module name with
This will import module but if we want to call the function
sum we should use following line which provides module name specifier.
This may be a bit trivial to specifying module name in every function or similar usage. We can commit module name by importing like below. We will use
from keyword and import all elements of the given module.
from mymodule import *
Here we can call without providing module name. We can implement this solutions mode multi level modules too like below.
from mymodule.math import *
Get Name of Module
We have imported module by using source file name by removing extension. We can get module name in application or interactive shell by calling
__name__ global variable.
List Module Functions, Attributes
Modules provides different variables, functions, sub-modules,attributes. We can list a module content with
dir function. The result will the list of names provided by module.