Skip to content
holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

Python Packages/Modules

An excellent and in-depth overview provides this article.

  • A *module is a .py file
  • A package is a collection of modules (usually a folder containing modules)

__init__.py files

If in a directory Python treats those as packages. This mechanism prevents unintentional packages to be shadowed. Any subfolder/subpackage must indclude a __init__.py file that it can be imported.

The __init__.py file can be empty or contain initialisation code for this package.

Do the imports

You have the following directory structure:


└── toplevel
    ├── ...
    ├── lib
    │   ├── __init__.py
    │   ├── sub
    │   │   ├── __init__.py
    │   │   └── myScript2.py
    │   ├── myLib.py
    │   └── ...
    ├── scripts
    └── ...
import lib.myLib

# lib.sub.myScript2.someFunction()        # does not work since it is a subpackage

# Works when importing:
import lib.sub
lib.sub.myScript2.someFunction()

Limit wildcard imports

Limit what is imported when from lib import * appears.

In __init__.py add a list named __all__ which states the modules to be imported:

__all__ = ["sub", "..."]

Intra-package references / import packages above your scope

Say myScript2 wants to use something in lib you can use absolute imports:

from toplevel.lib.myLib import blah
Clone this wiki locally