[Python-ideas] PEP for executing a module in a package containing relative imports

Jacob Holm jh at improva.dk
Sun Apr 22 02:04:04 CEST 2007

Ron Adam wrote:
> Jacob Holm wrote:
>> I find it very sad that PEP299 did in fact die, because I think it is 
>> much cleaner solution than the proposal that started this thread.
>> That said, I would like to se a way to remove the 
>> __name__=='__main__' weirdness. I am +1 on resurrecting PEP299, but 
>> also +1 on adding a "sys.main" that could be used in a new "if 
>> __name__=sys.main". I am -1 on adding a builtin/global __main__ as 
>> proposed, because that would clash with my own PEP299-like use of 
>> that name.
> I had at one time (about 4 years ago) thought it was a bit strange. 
> But that was only for a very short while.
To clarify: By "weirdness" here I meant the fact that the name of a 
module changes when it is used as the main module.

> Python differs from other languages in a very important way. python 
> *always* starts at the top of the file and works it way down until if 
> falls off the bottom. What it does in between the top and the bottom 
> is entirely up to you. It's very dynamic.
> Other languages *compile* all the code first without executing any of 
> it. Then you are required to tell the the compiler where the program 
> will start, which is why you need to define a main() function.
I know all that.

> In Python, letting control fall off the bottom in order to start again 
> at some place in the middle doesn't make much sense. It's already 
> started, so you don't need to do that.

There are a number of reasons to want to use a function for the main 
part of the code, instead of putting it in an "if" at the end of the 
module. Two simple ones are:

Keeping the module namespace clean.

The ability to call the function from other code, most likely with 
different args.

Since I am usually writing such a function anyway, I would prefer not to 
have to write the "if" boilerplate at the bottom in order to get it 
called. Oh, and automatically calling a __main__ function if it exists, 
does not prevent people who like the current "if" aproach from using 
that. It would just make *my* life that tiny bit easier.

Therefore I would like to keep that door open by *not* adding the 
proposed __main__ variable at this point. Fortunately, the people that 
matter here seem to think avoiding the extra variable is a good idea 
(although for different reasons).


Jacob Holm
Improva ApS

More information about the Python-ideas mailing list