What is a python module?
Till now we have seen all the code written in a single python file but real applications are made up of multiple python files.

Each python file is called a Module.

This module can be used in other python files of the same application or it can also be used in other applications provided it is available to them.

Writing an application using modules promotes reusability since same code can be used at multiple places.
Each module consists of one or more functions which can be called from other modules which have access to the owner module of those functions.

Practical use of Module
Suppose you have a file which contains some utility functions such as one which reads a text file and returns a list of lines, other which takes a format and returns current date, one which takes a directory path and returns a list of all files in it etc.
Now you need those functions in your code somewhere else, say in some other file.

One way is to copy the functions from that file into your file and then use them.
Another and a more better way is to import that module(or file) into your file and call its functions directly.
This way you can re-use the functions which are already written and save your effort and time.
It might be possible that the module you are importing has been written by some other person working with you.
It might also be possible that the imported module is written by someone you don’t know as it may have been downloaded from the Internet.

Module import
A module before being used needs to be imported. Once a module is imported into another module, its variables and functions can be accessed in the importing module.
A module(or file) is used in another module(or file) using import statement.
import is followed by the name of the file that needs to be imported.

While importing, the .py extension of file is not used.

Import module example

Suppose you have a python file which contains a function that takes a file name, reads its contents and returns a list of lines as shown below

# filereader.py

def read_file(filename):        # define a function
    filehandle = open(filename) # open file
    # read lines and store them in list
    filecontents = filehandle.read().splitlines() 
    filehandle.close()          # close file
    return filecontents         # return list

This function takes a file name as argument, reads its lines into a list and returns it.
Let the name of its file be filereader.py and can also be called a Module.

Now you want to develop a program which should read a file and print its contents.
Either you write the file reading code again or use the above module and save your effort.
Let’s name this file as filedisplay.py

# filedisplay.py

import filereader

file_contents = filereader.read_file("f:/fruits.txt")
print(file_contents)

Above code imports filereader and uses its file reading function. Note that the function from the imported module is called using syntax  <modulename>.functionname 

Importing required functions only
Many times only a single function is required from a module.
Thus, it is not necessary to import an entire file(or module) into another file. In such cases, it is also possible to import only selected functions or variables from a file(or module).

To import selected functions from a module, from keyword is used.
Syntax is

from <modulename> import <functionname>
Our previous example can be modified as

# filedisplay.py

from filereader import read_file

file_contents = read_file("f:/fruits.txt")
print(file_contents)

Note that now we are importing only a function from the specified module.
Thus, it is not necessary to prefix module name and dot while calling the function, it can be called directly using its name.

If a file contains a function with same name as imported function and the function is called using its name only, then the function defined in the same file will be called.

If you want to call the function defined in imported module, then use <filename>.<functionname> syntax.

When importing using the from import syntax, only the functions imported will be available.

In order to import all the functions using this syntax, write it as

from <modulename> import *

Importing Variables from Modules
Not only functions, but variables can also be imported from other modules. Example,

# utility.py

CITY_NAMES = ['California', 'Sydney, 'New York', 'London']

# returns square of supplied number
def square(number):
   return number * number;

Above file(utility.py) contains a list of cities and a function which calculates square of a number provided to it.
Now, let’s say, another module wants to use the list of cities, then it will get it as

# user.py

from utility import CITY_NAMES

cities = CITY_NAMES
print(cities)

Using the above syntax, square function will not be available to the importing file, it will have to separately import it.

Module path
In all the examples till now, we directly imported a file into another file.
But where should the files be places relative to each other?
For all the examples above to work, both the files should be placed adjacent to each other as shown below

project
   |— user.py
   |— utility.py

But what if the module(or python file) to be imported is placed in a folder and the module which requires it are not adjacent to each other but at different locations.
Example,

project
   |— user.py
   |— mod
         |— utility.py
Now if user.py wants to access functions of utility.py, then it will import it in a slightly different syntax as below.

# user.py

from mod.utility import CITY_NAMES

cities = CITY_NAMES
print(cities)

Note that it prefixes the folder name followed by a dot(.) before the module name.
In case, if the file utility.py is located in a hierarchy of folders such as A/B/C/utility.py, then it will be imported as

from A.B.C.utility import CITY_NAMES
.

Leave a Reply