Python Module: How to create and import custom modules in Python

  • 3


In our previous articles we have discussed “Python: What is python virtualenv and why we need it” and “How to install Python Pip on CentOS 7” and many more related to Python. In this article, we will learn to create and import custom modules in Python. Also, we will see What are modules in Python?

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for e.g.:, is called a module and its module name would be example_module.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide re-usability of code.

We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

Create Custom Module in Python

Let us create a module. Create file and add the following sample code.


def print_name(name):
   """This program display the name
   which passed to the function"""

   print "Hello : ", name

Import Modules in Python

We can import the definitions/functions inside a module to another module or the interactive interpreter in Python.
We use the import keyword to do this.

1. Python import prompt:

>>> import example_module
>>> example_module.print_name("Avinash")
Hello : Avinash

2. Python import statement:


# Import module example_module
import example_module

# Now you can call defined function that module as follows

3. Python from…import statement:


from math import pi
print("The value of pi is", pi)

Example Usage:

We have implemented a quick example for Ansible Tower Rest API usage, that shows how to create and import modules in python. Please visit GitHub for full code.

Avinash Pawar

An automation enthusiast who presently working as DevOps Engineer.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Avinash Pawar

An automation enthusiast who presently working as DevOps Engineer.