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

Introduction

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.: example_module.py, 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 example_module.py and add the following sample code.

#!/usr/bin/python

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:

#!/usr/bin/python

# Import module example_module
import example_module

# Now you can call defined function that module as follows
example_module.print_name("Avinash")

3. Python from…import statement:

#!/usr/bin/python

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

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Avinash Pawar

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

Leave a Reply