Organizing Modules

Learn how to organize modules by absolute and relative imports in Python.

Why do we need packages?

As a project grows into a collection of more and more modules, we may find that we want to add another level of abstraction, some kind of nested hierarchy on our modules’ levels. However, we can’t put modules inside modules; one file can hold only one file after all, and modules are just files.

Files, however, can go in folders, and so can modules. A package is a collection of modules in a folder. The name of the package is the name of the folder. We need to tell Python that a folder is a package to distinguish it from other folders in the directory. To do this, place a (normally empty) file in the folder named __init__.py. If we forget this file, we won’t be able to import modules from that folder.

Get hands-on with 1200+ tech skills courses.