What does it mean by top-level code

In this tutorial, Python if __name__ == __main__ Explained with Code Examples, the conclusion stated that reading the files will execute all top-level code, but not functions and classes. Isn’t any code that is not indented are considered top-level code?

For example:

x = 5 # top-level

def something(): # top-level
    pass

  def something_again(): # not top-level
        pass

What does it mean by executing all top-level except functions and classes?

Let’s add to your example:

x = 5 # top-level

def something(): # top-level
    pass

  def something_again(): # not top-level
        pass

if __name__ == "__main__":
    print("hello")

Save this code in test.py and run python test.py and this code will set x to 5, read in the function something and print hello. At this point, the function definition is only loaded and not executed because nothing has called it. If you change the bottom to

if __name__ == "__main__":
    something()

Now, something gets loaded and executed. The author appears to be emphasizing the difference between loading function/class definitions and executing them. And yes, top level code is unindented.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.