Python: How to Write a Module

By Xah Lee. Date: . Last updated: .

Simple Example of a Module

You can define functions, save it in a file, then later on, load the file and use these functions.

Save the following in a file and name it mm.py

def ff(n):
    return n+1

To load the file, use import mm, then to call the function, use mm.ff

# import the module
import mm

# calling a function
print mm.ff(5)

What is Python Module, Package

Python Package Structure

If you have multiple files, they make up a package. You put all files inside directory, possibly with nested sub directories. Like this:

pp
๐Ÿ”ธ__init__.py
๐Ÿ”ธd1
๐Ÿ”ธ๐Ÿ”ธ__init__.py
๐Ÿ”ธ๐Ÿ”ธf1.py
๐Ÿ”ธd2
๐Ÿ”ธ๐Ÿ”ธ__init__.py
๐Ÿ”ธ๐Ÿ”ธf2.py
๐Ÿ”ธd3
๐Ÿ”ธ๐Ÿ”ธ__init__.py
๐Ÿ”ธ๐Ÿ”ธf3.py
๐Ÿ”ธ๐Ÿ”ธdd1
๐Ÿ”ธ๐Ÿ”ธ๐Ÿ”ธ__init__.py
๐Ÿ”ธ๐Ÿ”ธ๐Ÿ”ธf4.py
๐Ÿ”ธ๐Ÿ”ธ๐Ÿ”ธf5.py

For example, in the above, you can load a module by:

import pp.d1.f1
import pp.d3.dd1.f4

Dir with __init__.py means that directory is part of the package. Python look at the dir structure and file names as module's name when import is called.

The file __init__.py is executed when that particular module in that directory is loaded. If you don't need any such init file, just create a empty file.

For example, if dir d1 does not have a __init__.py file, then import pp.d1.f1 won't work, because Python won't consider dir d1 as part of the package.

Similarly, pp must have a __init__.py. And, if you want import pp to automatically load d1/f1, then, in pp/__init__.py you must have import d1.f1.

Here's a summary:

Tip: Module names should be short and lower case only.

Note: the Python language does not have direct technical concept of โ€œmoduleโ€ nor โ€œpackageโ€. e.g. there's not keyword โ€œmoduleโ€ nor โ€œpackageโ€. These words are only used to describe the concept of libraries. Technically, Python language only has a sense of namespace, and is exhibited by keywords import, __name__, __all__, or recognized file name __init__.py, etc.

2014-04-09 Thanks to Kaito Kumashiro for correction. Thanks to Demian Brecht for suggestion.

Python, Paths and Module