Size: 1632
Comment:
|
← Revision 7 as of 2023-01-07 21:01:02 ⇥
Size: 1631
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 5: | Line 5: |
This should not be confused with Python's [[Python/DunderMethods|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. | This should not be confused with Python's [[Python/DunderMethod|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. |
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.
Contents
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