A Short Digression Into Multi-File Modules

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 the __init__.py file? Nothing. Everything. Something in between. The __init__.py file doesn’t need to define anything; it can literally be an empty file. Or you can use it to define your main entry point functions. Or you put all your functions in it. Or all but one.

A directory with an __init__.py file is always treated as a multi-file module. Without an __init__.py file, a directory is just a directory of unrelated .py files.

Let’s see how that works in practice.

Get hands-on with 1200+ tech skills courses.