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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.