I've been doing some serious thinking about changes to Python (both the
language and the implementation) that would significantly speed up the
One of my (many) ideas is to run a code optimization pass *after*
a module has initialized itself. The reason for doing it then is that
(with suitable language changes) we could guarantee that all global bindings
have been established. The code optimizer, could, for example, determine
that a particular call to 'range' is in fact bound to the builtin function
'range', and it could use this information to emit efficient code for
for i in range(1,10):
Unfortunately, there is no such thing as "after a module has initialized
itself" for Python scripts, because the initialization phase is identical
to running the script. So, one of the language changes required to make
my idea fly is this: a Python script is now required to contain a function
called 'main', which is called with the argument 'argv'.
This change seems to provide a nice solution to Steve's problem.
Steve has code that he wants executed when a module is run as a script,
but not when it is imported. Under the above proposal, all he has to
do is put this code into the function 'main'.
My proposal also provides the general ability to write modules that
import scripts, then create an argument list for that script, then
run the script with that argument list. For example,
args = [ ... ]
Actually, this proposal can be implemented without losing backward
compatibility. We change Python so that when it runs a script,
it first initializes it, then checks for a binding called 'main',
and calls it with sys.argv if 'main' exists. If there are already
a lot of scripts containing functions called 'main', then we modify
this proposal to use a different name, like '__main__' for instance.
That way, no existing code is broken.