DEV Community

Arseny Zinchenko
Arseny Zinchenko

Posted on • Originally published at rtfm.co.ua on

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

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.

Note: this post initially was written on 09/12/2014 in my Russian blog version so here is Python 2 used.

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:

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

The execution result of the Script 1 directly:

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

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 here:

#!/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:

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

While running the Script 1 – next:

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

Similar posts

Top comments (0)