[Python-ideas] Just __main__

anatoly techtonik techtonik at gmail.com
Tue Jun 19 09:52:36 CEST 2012

On Mon, Jun 18, 2012 at 9:59 PM, Jeremiah Dodds
<jeremiah.dodds at gmail.com> wrote:
> Andrew McNabb <amcnabb at mcnabbs.org> writes:
>> I'm not sure if a "__main__" function would add enough value, but I
>> think it would add more value than a "__main__" boolean.
> +1 .

My first thoughts is that __main__() as a function is bad for Python,
and here is why.

In C, Java and other compiled languages so-called main() function is
the primary execution entrypoint. With no main() there was no way to
instruct compiler what should be run first, so logically it will just
start with the first function at the top (and if you remember early
compliers - you can only call functions that are already defined, that
means written above yours). Code exection always started with main().
It was the first application byte to start with when program was
loaded to memory by OS.

In Python execution of a program code starts before the  if __name__
== '__main__'   is encountered (and it's awesome feature of a
scripting language to start execution immediately). With automagical
__main__() function it will also start before. That's why __main__()
will never be the substitution for the classical C style entrypoint.

In Python entrypoint is a module (entrypoint namespace). __name__ is
equal to '__main__' not only in a script, but also in console. And
__main__ as a flag in this namespace correctly reflects this semantic
- "Is this a main namespace? True". A value of __name__ in console

So, __main__() function is not equivalent to C/Java entrypoint.
However, a function like this may play an important role to mark the
end of the "import phase" or "initialization phase". A high level
concept that is extremely useful for web
applications/servers/frameworks, who need to know when an application
processes can be more effectively forked.

Here is one more problem - when module is executed as a script, it
loses its __name__, which becomes equal to '__main__'. I don't know if
it ever caused any problems with imports or consistency in object
space, or with static imports - it will be interesting to know any
outcomes. What if module __name__ always meant module name? But that's
another thread. As for __main__ - in this case instead of boolean it
could be the name of the entrypoint module, and the check would be  if
__name__ == __main__   without quotes.

More information about the Python-ideas mailing list