Saturday, July 15, 2017

Is __main__ guaranteed to always be importable?

Leave a Comment

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.

1 Answers

Answers 1

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment