Add an __imported__ flag to avoid the use of __name__ == '__main__'

Hi!

I’m a pretty frequent user of the python discord, and we often have questions about the use of

if __name__ == '__main__':
    #...

Python has this particularity of having a syntax very close to the natural language and pseudo-code, which makes it easy to learn and understand for a beginner. The issue with this expression is that this expression doesn’t have a self-documenting name, as the rest of the standard library does. Moreover, most tutorials that try to be beginner-friendly that I’ve seen use this expression without even explaining why it is here, neither how does it work, which is almost impossible to deduct just by looking at it.

My suggestion would be to use an __imported__ flag, that will be set to False by default, except on the ran file, where it would be True. This could allow the

if __name__ == '__main__':
    #...

To be shorten to

if not __imported__:
    #...

This would be more readable, and pretty much self-documenting. Additionally, it would keep the backward compatibility and be a really good introduction to the idea of dunders.

You might want to look at PEP 3122 for some ideas.

Except that it would be technically wrong, and confusing for whoever has some knowledge of the startup sequence. The main module is imported (under the name __main__, precisely).

3 Likes

It does not need changes in the Python interpreter. You can do it yourself:

__imported__ = __name__ != '__main__'
if not __imported__:
    #...

It is easier than write:

import sys
if (not __imported__) if sys.version_info >= (3, 9) else (__name__ == '__main__'):
    #...

or

if not globals().get('__imported__', __name__ != '__main__'):
    #...

Not mentioning that the name __imported__ is misleading because the main code is technically imported.