November 16, 2016

Modules and packages in Python 3

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


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



© Plogging Dev - Powered by Hugo Theme by Kiss