Swami Vivekananda

What are python modules?

14 Sep 2019 - fubar - Sreekar Guddeti

python-Logo The organization of python program is discussed with module as an entity.

Abstract

Modules form the highest organization structure in a Python program. The rationale behind modules lies in code reusability, a primary feature that Python wants you to do. Module also is a namespace, so that organizing a program is indirectly about managing namespaces. Namespaces is a recurring concept as discussed in Python functions and Python classes. In the following, we explain the internal process when modules are imported, how to search existing modules, and the various types of modules.


Module

What is a module?

Why use a module?

Code reuse

Namespace partitioning

Implementing shared services or metadata

How to access the module namespace?

The names of a module namespace can be accessed/imported by two statements and and one important function

the module file’s global scope morphs into the module object’s attribute namespace when it is imported.


Python Program architecture

Python-program-architecture-modules


Standard Library modules


How imports work


Module search path

Imports mention only the filename without extension, which is searched in a path formed by concatenation of following directories and the left most search result is taken as the file path.

import sys
print sys.path

Since only the filename without extension is searched, an import mod can resolve to any of the following files:


Summary

The idea of structuring program is the rationale behind modules. Modules act as namespaces so that names in one module cannot be seen by another module, unless the former is imported. This Python Program architecture helps in dividing the logic into self-contained components. In addition to the home directory and standard library modules, custom modules can be searched via the module search path setting the PYTHONPATH environment variable or .pth files in top-level. While importing a module, Pythons allows freedom to choose from a variety of file extensions like .py, .pyc, .pyo, .so or a directory also (as we will see in the next chapter).

References

Chapter “Modules: The Big Picture” of “Learning Python” by Mark Lutz.