0

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?

0

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

2 Comments

It worked almost exactly as you said, but the output was running test2 test instead of test 2
Thanks for specifying :) just tested it and modified the answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.