I want to understand from which point a Python program starts running. I have previous experience in Java. In Java every program starts from main() function of it's Main class. Knowing this I can determine the execution sequence of other classes or functions of other Classes. I know that in Python I can control program execution sequence by using __name__ like this:
def main():
print("This is the main routine.")
if __name__ == "__main__":
main()
But when we don't use __name__ then what is the starting line of my Python program?
1 Answer 1
Interpreter starts to interpret file line by line from the beginning. If it encounters function definition, it adds it into the globals dict. If it encounters function call, it searches it in globals dict and executes or fail.
# foo.py
def foo():
print "hello"
foo()
def test()
print "test"
print "global_string"
if __name__ == "__main__":
print "executed"
else:
print "imported"
Output
hello
global_string
executed
- Interpreter starts to interpret foo.py line by line from the beginning like first the function definition it adds to globals dict and then it encounters the call to the function
foo()and execute it so it printshello. - After that, it adds
test()to global dict but there's no function call to this function so it will not execute the function. - After that print statement will execute will print
global_string. - After that, if condition will execute and in this case, it matched and will print
executed.
python some_module__name__ == '__main__'to guard against executing code you might want to place inside a module but only want to execute it if it is the "main" module