re: What's the use of if __name__ == '__main__': in Python? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: 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 j...
 

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
code of conduct - report abuse