Directories and packages

Both directories and packages are ways to organize and structure your code. However, they serve slightly different purposes

Directories:

  • In Python, directories are simply folders on your file system that contain Python files (modules) or other directories.
  • They are used primarily for organizing and storing your Python source code files.
  • Directories themselves are not directly importable in Python. Instead, Python files within directories are imported as modules.

Packages:

  • Packages, on the other hand, are special directories that contain an additional __init__.py file. This file can be empty or can contain Python code.
  • The presence of the __init__.py file indicates to Python that the directory should be treated as a package.
  • Packages allow you to organize related modules (Python files) into a single namespace.
  • Packages can also contain sub-packages, which are simply packages within packages, forming a hierarchical structure.
  • When you import a package in Python, you are actually importing the __init__.py file of that package.

Suppose we have the following directory structure:

my_project/
├── main.py
└── my_packages/
    ├── __init__.py
    ├── package1/
    │   ├── __init__.py
    │   ├── module1.py
    │   └── module2.py
    └── package2/
        ├── __init__.py
        ├── module3.py
        └── subpackage/
            ├── __init__.py
            └── module4.py
  • my_project/ is the main directory of our project.
  • main.py is the entry point for our application.
  • my_packages/ is the parent package directory.
  • package1/ and package2/ are two packages within my_packages/, each with their own __init__.py files indicating they are packages.
  • subpackage/ is a sub-package of package2/.
  • Each package and sub-package can contain one or more modules, indicated by .py files.

Here's a brief example of what the files might contain:

main.py:

from my_packages.package1 import module1
from my_packages.package2 import module3
from my_packages.package2.subpackage import module4

module1.foo()
module3.bar()
module4.baz()