[Python-ideas] making a module callable

Nick Coghlan ncoghlan at gmail.com
Sun Nov 24 08:24:20 CET 2013


On 24 November 2013 02:53, Haoyi Li <haoyi.sg at gmail.com> wrote:
>> Are you serious that replacing __main__ is a bad idea? If so, can you
>> explain why?
>
> It also doesn't work, last I tried =( Strange things start breaking when you
> replace __main__

The main thing that makes __main__ special is that it's a builtin
module, but we then use its namespace to run Python code. Various
parts of the interpreter assume that __main__ will always be the same
module that was initialized during interpreter startup, so they don't
have to keep re-initializing it (or checking if it has been replaced).
It's not quite as intertwined with the interpreter internals as sys,
since there's no direct reference to it from the interpreter state,
but the case can certainly made that there *should* be such a
reference if we're going to assume consistency over the the lifetime
of the process.

However, while I can't vouch for earlier versions, replacing __main__
in 3.3+ shouldn't cause any major issues, although it does mean
certain things may not behave as expected (such as the -i switch and
the PYTHONINSPECT option).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list