DEV Community

Discussion on: What's the use of if __name__ == '__main__': in Python?

Collapse
 
prahladyeri profile image
Prahlad Yeri • Edited

Broadly speaking, it is the entry point of a python script or program and is comparable to the void main() of C++ or public static void main() of java.

Specifically, the __name__ built-in makes your module "know" whether its directly executing as a script/program or being imported as a module in another module. When its directly run, the built-in has a value of "__main__" and thus the following condition will hold true:

if __name__ == "__main__":
    pass # do something
Enter fullscreen mode Exit fullscreen mode

But if your module is being imported into another module, the above won't be executed and your module won't do anything (assuming everything else in your module are just functions and classes, and no directly executing code). But if you don't place the above if condition, then whatever is inside that block (# do something) will run each time irrespective of whether your module is executed directly or being imported.

Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable:

def main():
    # do something

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
orenovadia profile image
orenovadia

Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable

I agree that it is more neat, but more than that:

  1. It is faster
  2. It doesn't pollute the global namespace

For example, this foo function will work only if it the file is executed directly, but not if it is imported (bad, confusing and inconsistent):

def foo():
    for i in range(N):
        yield i

if __name__ == '__main__':
    N = 5
Enter fullscreen mode Exit fullscreen mode