How Does the Name-Main Idiom Work?
__name__ variable stores the name of a module when it’s loaded. So we’ll talk about module names in a bit, but first, a side note about dunder: there are many dunders in the Python language, both dunder variables and dunder methods.
01:07 And Python uses this weird naming convention to mark it as reserved for Python’s uses. They’re intentionally kind of ugly or weird or complex looking because a regular programmer would never want to use this naming convention in their own code.
01:25 It also makes it very obvious about what’s part of the Python language itself and what’s part of a program that someone has written in Python. You also shouldn’t be creating your own dunders because they might conflict with Python’s current dunders or ones that they might use in future Python versions.
The top-level code environment could be the REPL session, which is the global scope when you run Python in interactive mode, or the script passed to the Python interpreter as a file argument, which just means if you run
python file.py, then
file.py would be that script where that’s the top-level code environment.
When you run
python repeat.py as a script, Python sets
__name__ variable to
"__main__". Then it checks if
__name__ is equal to
"__main__" and that
if statement is
True, so it asks for user input and calls the
But now, what happens when you run
python lyrics.py? In
lyrics.py, the first line is
repeat function. As you learned in the previous lesson, this will actually execute
Then we’re using the name-main idiom and printing
"Got here" if it was
True. We can run this file as a script by saying
"__main__", and the class is a string. And it does print out
"Got here" because
__name__ was equal to
"__main__" in this case.
To summarize, the
if is just a regular conditional statement,
__name__ is a variable that stores the name of the module, and the string
"__main__" is the value of
__name__ when you’re in the top-level code environment.
Become a Member to join the conversation.