Python: How to Write a Module

By Xah Lee. Date: . Last updated: .

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

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:


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

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

Dir with 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 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 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 And, if you want import pp to automatically load d1/f1, then, in pp/ 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, etc.

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

Python, Paths and Module