Search code examples
pythonsequenceexecution

What is the entry point of Python program of multiple modules?


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?


Solution

  • 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 prints hello.
    • 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.