Search⌘ K

A Short Digression Into Multi-File Modules

Explore the concept of multi-file modules in Python by examining how a directory with an __init__.py file works as a single module. Understand how relative imports enable modular code organization and see practical examples from the chardet library. This lesson helps you manage growing Python projects by structuring them into manageable multi-file modules.

We'll cover the following...

chardet is a multi-file module. I could have chosen to put all the code in one file (named chardet.py), but I didn’t. Instead, I made a directory (named chardet), then I made an __init__.py file in that directory. If Python sees an __init__.py file in a directory, it assumes that all of the files in that directory are part of the same module. The module’s name is the name of the directory. Files within the directory can reference other files within the same directory, or even within subdirectories. (More on that in a minute.) But the entire collection of files is presented to other Python code as a single module — as if all the functions and classes were in a single .py file.

What goes in ...