What is a top-level statement in Python?

后端 未结 3 1513
长情又很酷
长情又很酷 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:35

    Here's the first mention of "top-level statement":

    Once modu.py is found, the Python interpreter will execute the module in an isolated scope. Any top-level statement in modu.py will be executed, including other imports if any. Function and class definitions are stored in the module’s dictionary.

    This makes it clear that what they really mean is "things that are interpreted at import time".

    While it's not terribly helpful directly, the Python documentation itself also uses the phrase "top-level" (components, which then means "statements" in this context).

    Note that this module:

    """a python module, spam.py"""
    
    def spam():
        return "spam"
    
    class Spam(object):
        pass
    

    has two statements in it, the def and the class. These are both executed at import time. These definitions are compound statements (see def and class descriptions). If there are decorators attached to a top-level def, that adds even more top-level things to run. (See also user2357112's answer: running a class statement invokes more internal workings.)

    Add an import sys at the top and you've added a third statement, which imports sys. However, if you add this:

    def ham(eggs):
        import os
        return os.path.basename(eggs)
    

    you have still only added one statement, the def ham, to the top-level stuff. It's when ham itself is executed (called) that the import os will be run.

提交回复
热议问题