Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is __main__ guaranteed to always be importable?

Is there any case where doing:

import __main__

might lead to an ImportError? All cases I've tried seem to indicate that this always works. The docs on __main__ don't seems to state anything on the matter.

To give some context: I am trying to inject some names in __main__.__dict__ using the usersitecustomize hook in order to (mainly) have them available when the REPL fires up.

Granted that no redefinitions of __import__ occur (as a comment stated), this essentially boils down to if I need to wrap it in a try-except or not.

like image 886
Bob Holver Avatar asked Nov 19 '25 01:11

Bob Holver


1 Answers

It probably is. Python initializes __main__ in this file: https://github.com/python/cpython/blob/master/Python/pylifecycle.c#L1327

However please note that modules like runpy and IPython replace the __main__ module with their own dynamically created ones to prevent collisions with their own launch scripts and to provide expected behaviour in case of runpy.

runpy itself is part of the Python Standard Library and provides the implementation of the -m flag which allows arbitrary modules to be executed as script.

An alternative is IPython which offers the feature to execute code at the launch of a new REPL.

For more details, see here: http://ipython.readthedocs.io/en/stable/config/intro.html?highlight=exec_lines

like image 150
StuxCrystal Avatar answered Nov 20 '25 14:11

StuxCrystal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!