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?
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
foo()
and execute it so it prints hello
.test()
to global dict but there's no function call to this function so it will not execute the function.global_string
.executed
.