What is a top-level statement in Python?

后端 未结 3 1523
长情又很酷
长情又很酷 2021-02-07 22:09

In the Python Guide\'s chapter on project structure, the term \"top-level statement\" is brought up a few times. I\'m not sure exactly what this refers to. My guess is it\'s any

3条回答
  •  余生分开走
    2021-02-07 22:28

    It's not just variable declarations (and there aren't any variable declarations anyway). It's pretty much anything that starts at indentation level 0.

    import sys         # top-level
    
    3 + 4              # top-level
    
    x = 0              # top-level
    
    def f():           # top-level
        import os      # not top-level!
        return 3       # not top-level
    
    if x:              # top-level
        print 3        # not top-level
    else:
        print 4        # not top-level, but executes as part of an if statement
                       # that is top-level
    
    class TopLevel(object): # top-level
        x = 3          # not top-level, but executes as part of the class statement
        def foo(self): # not top-level, but executes as part of the class statement
            print 5    # not top-level
    

提交回复
热议问题