DEV Community

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

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