Is __main__ guaranteed to always be imported?
Are there any cases when you do:
import __main__
can lead to ImportError
? All the cases I've tried show that this always works. The docs __main__
don't seem to say anything about this.
To give some context: I am trying to insert some names in __main__.__dict__
with a hook usersitecustomize
to (mostly) have them available when the REPL starts up.
Assuming no overrides __import__
are encountered (as pointed out in the comment), it essentially boils down to whether I need to wrap it in try-except
or not.
source to share
Likely. Python initializes __main__
in this file:
https://github.com/python/cpython/blob/master/Python/pylifecycle.c#L1327
Note, however, that modules of type runpy
and IPython
replace the module __main__
with their dynamically created ones to prevent conflicts with their startup scripts and to provide the expected behavior in the case of runpy.
runpy itself is part of the Python standard library and provides a flag implementation -m
that allows arbitrary modules to be executed as a script.
An alternative is IPython, which offers a function to execute code when a new REPL starts.
See here for details: http://ipython.readthedocs.io/en/stable/config/intro.html?highlight=exec_lines
source to share