5

I came across a line in python:

def somefunc:
    [...]

if __name__ == '__main__':
    somefunc

I don't understand what the "if __name ..." does.

Suppose we have:

if __name__ == '__main__': main()

#this code will find main

So is this similar to the main() function in C/C++, which gets executed before any other function?

Josh
  • 3,231
  • 8
  • 37
  • 58

2 Answers2

9

If you execute your script directly, without importing it, __name__ will be equal to __main__. But if you import this file, __name__ will be equal to the name of the module importing it. This condition makes sure you execute your code from this file.

1

you can think this as the main() in C or the BEGIN { } block in perl.

when you run the code using python file1.py.

__name__ in file1.py is equal to '__main__', but in other files imported by file1.py, the variable is something else.