Python Forum

Full Version: Strange the name of the file is changed automaticaly
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
#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__': 
"""
  
  
  
  
  
  
It's not the name of the file. It's a name of the scope.

https://docs.python.org/3/library/__main__.html

Quote:'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

foo.py
import bar
print(__name__)
bar.bar()
bar.py
def bar():
    print(__name__)
if you run foo.py the output would be
Output:
__main__ bar
Can I consider that the first time the interpreter executes my file, it considers my file as __main__, and executes what is after the "if __name__ == "__main__" statement.
But if this file is imported by a second file, it no more executes what is under "if __name__ == "__main__" ???
(Jun-05-2018, 06:37 PM)sylas Wrote: [ -> ]Can I consider that the first time the interpreter executes my file, it considers my file as __main__, and executes what is after the "if __name__ == "__main__" statement.

not only the first time, but every time when you execute your file

(Jun-05-2018, 06:37 PM)sylas Wrote: [ -> ]But if this file is imported by a second file, it no more executes what is under "if __name__ == "__main__"

yes, that is correct.
Actually read one more time my answer that you quote in your first post