lundi 4 juillet 2016

Why does running a submodule (python -m a.c) also import the containing module?


Given:

tree

~/dir                                                                          
▶ tree
.
├── a
│   ├── __init__.py
│   ├── c.py
└── b.py

1 directory, 3 files

*.py files

~/dir                                                                          
▶ tail -n +1 **/*.py                                                  
==> a/__init__.py <==
print(__name__)
import a.c

==> a/c.py <==
print(__name__)

==> b.py <==
print(__name__)
import a

I/O

~/dir                                                                          
▶ python3 -m a.c
a
a.c
__main__

Module a.c has no dependencies on module a. So, why does Python run module a as if it were importing it? To me this is surprising behavior. I didn't expect running a script without imports would cause the script itself to be imported and evaluated twice. Wouldn't this be dangerous for the scripts that don't use the protection of if __name__ == "__main__"?

What is the justification for this behavior? Why does Python need to evaluate the containing module upon running its submodule?


Aucun commentaire:

Enregistrer un commentaire