Every module in python has a special attribute called __name__ . The value of __name__ attribute is set to '<strong>main</strong>' when module run as main program. Otherwise the value of __name__ is set to contain the name of the module.

Consider the following code for better understanding.

1

2

3

4

5

6

7

8

9

10

11

# file my_module.py

foo=100

defhello():

print("i am from my_module.py")

if__name__=="__main__":

print("Executing as main program")

print("Value of __name__ is: ",__name__)

hello()

Here we have defined a new module my_module . We can execute this module as main program by entering the following code

1

python my_module.py

Expected Output:

1

2

3

Executing asmain program

Value of __name__ is:__main__

iam frommy_module.py

here we are creating a new module and executing it as main program so the value of __name__ is set to '<strong>main</strong>' . As a result if condition satisfies and hello() function gets called. Now create a new file called module.py and write the following code

1

2

3

4

5

6

importmy_module

print(my_module.foo)

my_module.hello()

print(my_module.__name__)

Expected Output:

1

2

3

100

iam frommy_module.py

my_module

As you can see now if statement in my_module fails to execute because the value of __name__ is set to 'my_module' .

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!