14 Sep 2019 - fubar - Sreekar Guddeti
The organization of python program is discussed with module as an entity.
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.
Code reuse
Namespace partitioning
Implementing shared services or metadata
The names of a module namespace can be accessed/imported by two statements and and one important function
import
statement fetches a whole module.from
statement fetches particular names from a module.reload()
function of the imp
module reloads a module without stopping Python.
All names defined at the top level of module file become attributes of the imported module object. In OOP jargon,the module file’s global scope morphs into the module object’s attribute namespace when it is imported.
os
, sys
), object persistence, text pattern matching (re
), network (requests
) and Internet scripting, GUI construction (tkinter
)#include
, which are textual insertions of file into another, Python’s import
are runtime operations involving
.pyc
file. Unless the source code is modified, subsequent imports simply reuses the byte code.
.pyc
speed future imports.__name__
and __main__
are used.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.
PYTHONPATH
directories.site-packages
subdirectory in the Python installation for listing the third-party extensions.
path
attribute of the sys
standard modulesimport sys
print sys.path
Since only the filename without extension is searched, an import mod
can resolve to any of the following files:
-O
flag).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).
Chapter “Modules: The Big Picture” of “Learning Python” by Mark Lutz.