Python: How to Write 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
- A module is a single file of Python code.
- A package is a directory of Python modules. (but can mean a single file module too.)
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:
- When you Import Module, Python searches for modules at Module Search Paths.
- Module files are just regular Python code. No special requirement on file content. No special declaration needed.
- A package is directory of modules.
- A package's directory must have
__init__.py
file, but can be empty file. This file is loaded when modules in that dir is imported. - File names and directory structure are automatically taken to be the module's name and form namespace. e.g. a dir named
a/b/c.py
is a module that can be imported withimport a.b.c
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.