Differences between revisions 2 and 3
Revision 2 as of 2020-02-24 18:56:57
Size: 1561
Comment:
Revision 3 as of 2020-02-24 18:57:14
Size: 1598
Comment:
Deletions are marked like this. Additions are marked like this.
Line 17: Line 17:
    +-- foo.py
Line 20: Line 21:
        +--- foo.py

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
    +-- foo.py
    +-- submodule
        +--- __init__.py
        +--- __main__.py
        +--- foo.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/foo.py
This is module.foo

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

$ python3 module/submodule/foo.py
This is module.submodule.foo

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

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

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

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


CategoryRicottone

Python/DunderFiles (last edited 2023-01-07 21:01:02 by DominicRicottone)