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.