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 module_demo.py is created.
  • A directory named modules is created.
  • The modules directory contains an empty __init__.py to signify that it is a package.
  • In the modules package, a useless_print.py file is created, which is a module.
  • To demonstrate submodules, a submodule directory is created inside modules.
  • Inside submodule, an __init__.py file is created to signify that it is a package.
  • Inside submodule, a module named another_print.py is created.
  • The functions useless_print and another_print from the modules by the same name are imported into module_demo.py.
  • The imported functions are invoked from module_demo.py.

Output:

text
some more text
some more text

By adding

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 __main__.

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.
  • Avoid 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

References: