Python Dunder Files

Python has a complex behavior defined around executing modules. This revolves around a set of 'dunder' files, chiefly 'init.py' and 'main.py'.

This should not be confused with Python's dunder methods. Python is well known for the ease of subclassing built-in types. This is accomplished through inheritance and shadowing specifically-named methods, in a manner approaching a protocol. Dunder files have nothing to do with any of these topics, but are so-named to appear familiar.

Demonstration

Consider a project structured as:

project
+-- module
    +-- __init__.py
    +-- __main__.py
    +-- submodule
        +--- __init__.py
        +--- __main__.py

Every '.py' file is written as:

print('This is <FILENAME>')

Observe the behavior of Python depending on how it is executed.

$ python3 module
This is module.__main__

$ python3 module/submodule
This is module.submodule.__main__

$ python3 -m module
This is module.__init__
This is module.__main__

$ python3 -m module.submodule
This is module.__init__
This is module.submodule.__init__
This is module.submodule.__main__


CategoryRicottone