Python Forum

Full Version: Problem with __main__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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__' ?
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
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.