A module is a file that contains Python definitions and statements with a
.py extension. So technically,
all the code that I posted so far has been in the form of modules. Modules are a way to organize code
in Python so that closely related functions and definitions are grouped together into a module.
It makes code reusable.
A related concept is packages. Packages are just a way to organize modules into a namespace. A package
can be thought of as a directory that contains modules and subpackages. For Python to treat a directory as
a package, a file named
__init__.py is required in the directory. The
__init__.py can also contain
code that will be executed when the package is first imported, typically initialization code.
The following example clarifies these concepts:
- A file named
- A directory named
modulesdirectory contains an empty
__init__.pyto signify that it is a package.
- In the
useless_print.pyfile is created, which is a module.
- To demonstrate submodules, a
submoduledirectory is created inside
__init__.pyfile is created to signify that it is a package.
submodule, a module named
- The functions
another_printfrom the modules by the same name are imported into
- The imported functions are invoked from
text some more text some more text
if __name__ == "__main__": import sys #pass sys.argv to relevant function
a module can be used as a script and a module. Executing the module with
python module.py arguments , the code in the module will be executed, just as if you imported it, but with the
__name__ set to
The source code can be found in the repository.
A few notes about modules and packages in Python:
- Be explicit: import only what is required.
from modules import *. It clutters the namespace and can result in namespace clashes.
- Avoiding nesting modules as far as possible, prefer a flat structure. For the purpose of demonstration, I nested a module two levels deep.
- Intra package references info