Python

Python: what if __name__ == “__main__” does?

December 17, 2021

Python: what if __name__ == “__main__” does?

In this article we’ll see in detail what if __name__ == “main” does, a statement we sometimes come across in libraries, for example.

what if __name__ == “__main__” does cover

Hey you programmer, okay? Let’s learn more about Python!

This instruction is sometimes found in third party libraries/code and seems a bit mysterious, what does it do?

Basically we can understand that when our code from one file is not imported into another __name__ will be __main__

When our foo.py file, for example, is imported into the bar.py file

The value of __name__ becomes bar.py, in the foo.py file

In bar the __name__ is still __main__, as it is the ‘main’ file

See the examples down below:

def printSomething():
 print("Print only if __name__ is __main__")
 if(__name__ == "__main__"):
  printSomething()
 else:
  print("__name__ is not __main__")

In this case we will have the the following print:

Print only if __name__ is __main__

Because __name__ is __main__, it is the main file running

Now let’s see what happens if we import foo.py into this bar.py file:

import foo

print("name in bar is: " + __name__)

We will have the following output if we run bar.py:

__name__ is not __main__

This is due to the fact explained above, the file foo was imported

So the name of __main__ is changed too

And the validation if __name__ == “__main__” is only True, when this file is not imported in others

Conclusion

In this article we learned  what if __name__ == “main”: does and how we can use it

The idea is that the __name__ is only __main__ in your file, when it is not imported into others

If it’s imported, its __name__ will be the name of the file, when called by this other file it was imported into

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x