Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with __main__
#1
Hi all. I saw many times files using 'if __name__=='__main__':' even file is a standalone file.
It seemed to me I should use this 'if' only in case of a project, using many files.
def fib(n) :
    a,b= 0,1
    for x in range(n):
        print(a,end=' ')
        c=b;b=a+b;a=c
        
  
fib(9)
print('')
if __name__=='__main__':
	print("why this line is printed since the name of the file is 'fibo.py' and not '__main__' ? ")
	
Output:
C:\Users\Sylvain\fs λ python fibo.py 0 1 1 2 3 5 8 13 21 why this line is printed since the name of the file is 'fibo.py' and not '__main__' ?
Reply
#2
There is no harm in using for a single script, it work same for one as for all.
Even when your project includes 5 scripts, at some point you only have 1.
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
Reply
#3
The point with if __name__=='__main__': has nothing to with one or many files.
If just run code it makes no difference.

It has to do with import(so code do run when import it).
# my_module.py
def foo():
    return 42

if __name__ == '__main__':
    print(foo())
Run it:
C:\1
λ python my_module.py
42
So will try to import my_module:
C:\1
λ ptpython
>>> import my_module

>>> my_module.foo()
42
If work as wanted,i have to call foo() to run it.

Now gone take away if __name__ == '__main__':
# my_module.py
def foo():
    return 42

print(foo())
Then try to import it.
C:\1
λ ptpython
>>> import my_module
42
The code run when i imported it,in most cases not what's wanted when import stuff.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __name__ and __main__ in functions Mark17 3 721 Oct-12-2023, 01:55 AM
Last Post: deanhystad
  question about if __name__=="__main__" aaander 6 1,341 Nov-13-2022, 09:06 PM
Last Post: deanhystad
  if __name__=='__main__' albin2005 3 2,127 Sep-07-2021, 09:21 AM
Last Post: albin2005
  ModuleNotFoundError: No module named '__main__.vtt'; '__main__' is not a package MM2018 26 16,807 Oct-12-2018, 05:40 AM
Last Post: MM2018
  Why do we use __main__ when we can call a function directly? Dave7Swift 5 3,837 Jun-04-2018, 05:01 AM
Last Post: Dave7Swift
  [split] can't find '__main__' module Blue Dog 1 9,463 Oct-18-2016, 12:23 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020