1

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?

9
  • 1
    by default the starting line is always the first line, just keep in mind that functions don't call themselves. Commented Jun 6, 2018 at 7:47
  • 1
    Python programs start executing at the beginning of the file, and code is executed line-by-line. Any imports will execute the entire imported file (and any files imported in that file etc etc) Commented Jun 6, 2018 at 7:48
  • But when I have multiple modules then first line of which module will run at first? Is it randomly selected? Commented Jun 6, 2018 at 7:50
  • 3
    @TaohidulIslam no, it is the module you start yourself with python some_module Commented Jun 6, 2018 at 7:51
  • 2
    Yes, but it's a module, not a class. But again, that's also how Java works. The only difference is the entry point into that file. And the fact that Python will execute all the source-code in a module, hence the use of __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 Commented Jun 6, 2018 at 8:02

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.