Should I start a Python program with:
if__name__ == '__main__': some code...
And if so, why? I saw it many times but don’t have a clue about it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do ‘import foo’ from another python file,
__name__evaluates to'foo', but if you run ‘python foo.py’ from the command line,__name__evaluates to'__main__'.Note that you do need to insert a space between if and _, and indent the main program: