[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Chris Angelico rosuav at gmail.com
Sun Nov 24 04:31:30 CET 2013


On Sun, Nov 24, 2013 at 11:37 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, Nov 24, 2013 at 09:04:59AM +1100, Chris Angelico wrote:
>
>> Just a really crazy idea... Does Python let you go "one level outside"
>> and tinker with the code that imports __main__? I haven't looked into
>> all that mechanism, but I know quite a bit of it is now implemented in
>> Python, so it's theoretically possible... could you, in effect, add a
>> line of code *after* that import that effectively calls
>> __main__.__main__(sys.argv) ? That would do most of what you want.
>
> It sounds like you're describing an import hook, although such things
> are completely opaque to me. I know they exist, but I've got no idea how
> they work or what they can do.

I was more trying to get to the surrounding code. When a binary is
executed, you fork a new process and exec it (on Unix). When a Python
script is executed, something somewhere effectively goes:

sys.argv = argv[1:]  # trim off the 'python' and keep the rest
import argv[1] as __main__
sys.exit()

If that code exists in Python somewhere, or if you can in some way
tinker with it, it would be possible to insert a call:

import argv[1] as __main__
try:
    main = __main__.__main__
except NameError:
    main = lambda: None
main()
sys.exit()

or similar. I could easily spin up a little C program that embeds
Python, and then tinker with the exact startup sequence; is there a
convenient way to do that in Python itself?

Of course, it'd always be possible to rig something that gets invoked as:

$ python3 x.py my_script_file.py

but I'd rather replace the current startup code rather than augment it
with another layer of indirection (and another file of code in the
current directory). This would be a convenient way to experiment with
theories like this, without fundamentally changing anything. What I'm
thinking of here is how Pike (yeah, borrowing ideas again!) allows you
to choose a different master; the default master does certain setups
and then calls on your code, and by changing the master you can tinker
with that. Normally you wouldn't need to, but it does make certain
types of experimentation very convenient.

ChrisA


More information about the Python-ideas mailing list