From what I understand, the following statement is used to make the program only run a branch if the program is run standalone.
if __name__ == '__main__':
What are other values the __name__
variable can assume, and what are its uses?
From what I understand, the following statement is used to make the program only run a branch if the program is run standalone.
if __name__ == '__main__':
What are other values the __name__
variable can assume, and what are its uses?
The if __name__ == "__main__"
: ... trick exists in Python so that our
Python files can act as either reusable modules, or as standalone programs.
When our scripts are used as standalone programs than __name __
is __main__
But When we run our script from some other module the variable __name__
assumes name of its module, so we know from that the script is being imported and not called from interactive prompt.
For ex make a script test.py
with a simple stamtement in it:
print __name__
Now now from cmd
when you do :
>>>python test.py
>>>__main__ #you get this output
Now let us assume you are import this in some other module (say test2.py
) and its contents are:
print "running test2"
import test
Then you would get this output:
running test2
test