While learning python programming language we generally write some code or sample applications. But these will generally consist of a few lines of code below 100 lines. In real-world applications the 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 are 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.
Create a Module
Creating a module is as 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 def sum(a,b): return a+b
Module Search Path
We have created a 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 a search path to locate modules named PYTHONPATH
. Python follows below step to search and load modules
- Look current working directory
- Look
PYTHONPATH
environment variable provided directories - Installation dependent default
Set PYTHONPATH
As previously stated we can provide a module directory different way. The most reliable way to set modules path is setting PYTHONPATH
environment variable. We will run this command in the 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.
$ PYTHONPATH=PYTHONPATH:/home/ismail/modules
Import Python Module
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 the module with import
directive by specifying the module name with .py
extension.
import mymodule
This will import module but if we want to call the function sum
we should use the following line which provides module name specifier.
mymodule.sum(2,3)
This may be a bit trivial to specifying module names in every function or similar usage. We can commit the module name by importing like below. We will use from
keyword and import all elements of the given module.
from mymodule import * sum(2,3)
Here we can call without providing a 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 the module by using the source file name by removing the extension. We can get the module name in the application or interactive shell by calling __name__
global variable.
mymodule.__name__
List Module Functions, Attributes
Modules provide different variables, functions, sub-modules, attributes. We can list a module content with dir
function. The result will the list of names provided by the module.
dir(math)

2 thoughts on “Python Modules Tutorial With Examples”