⇤ ← Revision 1 as of 2020-02-18 16:45:18
Size: 1248
Comment:
|
Size: 1561
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 35: | Line 35: |
$ python3 module/foo.py This is module.foo |
|
Line 37: | Line 40: |
$ python3 module/submodule/foo.py This is module.submodule.foo |
|
Line 42: | Line 48: |
$ python3 -m module.foo This is module.__init__ This is module.foo |
|
Line 46: | Line 56: |
$ python3 -m module.submodule.foo This is module.__init__ This is module.submodule.__init__ This is module.submodule.foo |
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/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