Whats exactly If __name__ == "__main__"  ?

Whats exactly If __name__ == "__main__" ?

If __name__ == "__main__" for Python Developers.

Table of contents

No heading

No headings in the article.

If the name equals main - then we run our programs! But do we actually understand what is name, what the main is, and most of all - why do we need to check if they match? 🤔🤔🤔 I've prepared this extraordinary tutorial that dives deep into each component and demonstrates it through simple code examples. By the end of this article - you'll be able to explain this expression in your own words (!!!) as well as other terms like "module" and even "top-level code" 😉

What is a module?

The module is like a code library that can be used to borrow code written by somebody else in our python program. There are two types of modules in python:

Built-in Modules - These modules are ready to import and use and ship with the python interpreter. there is no need to install such modules explicitly.

External Modules - These modules are imported from a third-party file or can be installed using a package manager like pip or conda. Since this code is written by someone else, we can install different versions of the same module with time.

What is __name__ ?

if name == "main"

a built-in variable called name variable represents a current module variable name is set to value main by default when running the current module. if name == "main": used to represent an entry point python .py (entry point)

Why do we need to check if __name__ == "__main__" ?

name == "main" reasons for using if __name__ == "__main__" You need to indicate the entry point of a project. We don't want to accidentally execute any statements in the packages we create.