Python: what is the if __name__ == “__main__” ?

By | 03/03/2019

PythonIn many Python modules you can find construction like:

if __name__ == "__main__":
    func()

Its main purpose is to dedicate a code which will be executed during calling code as a module, after importing it into another code – and when running module itself as a dedicated script.

Let’s take a look at a couple of examples.

Script 1:

#!/usr/bin/env python

print('Script 1. My name is: %s' % __name__)
print('This is simple code from script 1')

def func():
        print('This is code from function from script 1')

if __name__ == "__main__":
    func()

And Script 2:

#!/usr/bin/env python

print('Script2. My name is: %s' % __name__)
print('Importing ifname1')
import ifname1

The execution result of the Script 2 directly:

[simterm]

$ ./ifname2.py
Script2. My name is: __main__
Importing ifname1
Script 1. My name is: ifname1
This is simple code from script 1

[/simterm]

The execution result of the Script 1 directly:

[simterm]

$ ./ifname1.py
Script 1. My name is: __main__
This is simple code from script 1
This is code from function from script 1

[/simterm]

Another example.

Script 1:

#!/usr/bin/env python

if __name__ == "__main__":
    print('I am running as an independent program with name = %s' % __name__)
else:
    print('I am running as an imported module with name = %s' % __name__)

And Script 2 – no changes:

#!/usr/bin/env python

print('Script2. My name is: %s' % __name__)
print('Importing ifname1')
import ifname1

Executing the Script 2 will give us the next result:

[simterm]

$ ./ifname2.py
Script2. My name is: __main__
Importing ifname1
I am running as an imported module with name = ifname1

[/simterm]

While running the Script 1 – next:

[simterm]

$ ./ifname1.py
I am running as an independent program with name = __main__

[/simterm]