Jun-05-2018, 01:15 PM
Hi all! I find very strange that the name of the file is changed automatically. What becomes the first name I gave to my file: about_main.py
I think buran is very well placed to answer this.
I think buran is very well placed to answer this.
#about_main.py
def funct():
print("Value of __name__ is: ", __name__)
print('This statement is in main function')
def someFn():
print ('This function is not called under the main function')
someFn()
if __name__ == "__main__":
funct()
"""
Output
This function is not called under the main functon
Value of __name__ is: __main__
This statement is in main function
*******************************************************
People use __name__ to determine if the script is being imported or not. If it's equal to "__main__" then it's not an import. The idea being, you want to
run your main method if and only if you're not being imported. .
***********
just to add to micseydel's answer. Given your sample code
if you execute your script it will execute both functions (because of line 9 and line 11-12)
if you import it in another script it will execute someFn (because of line 9) but will not execute the other one
*******************************
yes, you can just call them.
As to which is better - in my opinion it's better to get the habit of using if __name__ =='__main__':
"""
