2

I am trying to understand that when we execute a .py file, then from which part of that code the python start the execution from? E.g.when we execute a Java program, the "public static void main(String[] args)" is the location where the java start the code execution. So, when we talk about python, how does it work? I know there is a python main function

(__name__ = "__main__") 

, I have gone through some article in and out of the Stackoverflow, they all say that it loads the python module, and then the python UDFs etc. So, as per my understanding, it is the location which is executed first thing. Please correct me, or guide me to some web links for my query.

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
user3521180
  • 1,044
  • 2
  • 20
  • 45
  • I have gone through the other article, so as per my understanding, whenever we execute the .py, first all the UDFs will be called upon, and then (__name__ = "__main__") . right? – user3521180 Aug 23 '17 at 13:27
  • As far as I understand it you only need `(__name__ = "__main__") ` if you want your code to be used as a library in Python. – Claudio Brasser Aug 23 '17 at 13:28
  • it doesn't answer my question, what if I do not wish to use my code as library? – user3521180 Aug 23 '17 at 13:30
  • Check out [this](https://stackoverflow.com/questions/287204/python-program-start#287215) question. – Claudio Brasser Aug 23 '17 at 13:30
  • I have already gone through that post, and I am coming from there to ask this question. – user3521180 Aug 23 '17 at 13:32
  • Here is an online tool that will help you: http://www.pythontutor.com/visualize.html#mode=edit – diek Aug 23 '17 at 13:39
  • As Python is a script language the execution starts at the top of the file and continues to execute the code top-to-bottom. Generally the first thing done are import statements as they are often at the top of a script. The `__name__ ` variable is set to `main` if the script is executed as the main function and not loaded by some other module. And the `(__name__ = "__main__") ` is used to distinguish between these two cases. The `name == main` part is not executed first, it's only to separate from where the script is called. Does that help your understanding? – Claudio Brasser Aug 23 '17 at 13:41
  • Python code gets executed line-by-line. – juanpa.arrivillaga Aug 23 '17 at 14:56

1 Answers1

2

If the Python code is in a method, no code will be executed unless you explicitly call the method (e.g. after checking __name__ == '__main__'). It is convention to call main method, but you can call any method as the starting point of execution.

If the Python code is not in a method, the code will be executed anytime you run or import the file.

jem
  • 130
  • 8