[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)
Rob Cliffe
rob.cliffe at btinternet.com
Mon Nov 25 16:10:43 CET 2013
On 25/11/2013 14:12, Steven D'Aprano wrote:
> (4) Like #3 above, but make it a (read-only?) global variable, like
> __debug__. Possibly spelled "__main__". The idiom becomes:
>
>
> if is_main:
> ...
>
>
> if __main__:
> ...
>
>
> Pros:
>
> - Some people might feel that "this is the main module" feels
> more like a global variable than a function call.
>
> Cons:
>
> - If read-only, that requires some magic behind the scenes.
>
> - If not read-only, then people will mess about with it and
> get confused.
>
> +0.5 if read-only, -0.5 if not.
>
I like this idea (a global variable called __main__), provided that it
can be implemented without slowing down access to other variables.
Say __main__ did not exist as a real variable, so attempting to read it
triggered a NameError behind the scenes.
The error handling code could then check for a name of '__main__' as a
special case. Does this make sense?
Con:
A variable which changes its value without being assigned to is more
magical/unexpected than a function
(is_main()) which returns different values at different times.
But I think people would soon get used to it, and find it convenient.
The behaviour could be overridden (if the run-time allowed it) by
defining a "real" variable called __main__.
Well, among consenting adults, why not? It might even be useful.
Rob Cliffe
More information about the Python-ideas
mailing list