<spanid="prog-structure"></span><spanid="index-0"></span><h2><spanclass="section-number">4.1. </span>Structure of a program<aclass="headerlink" href="#structure-of-a-program" title="連結到這個標頭">¶</a></h2>
<pid="index-1">A Python program is constructed from code blocks.
A <emclass="dfn">block</em> is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block. A script file (a file given as
standard input to the interpreter or specified as a command line argument to the
interpreter) is a code block. A script command (a command specified on the
interpreter command line with the <aclass="reference internal" href="../using/cmdline.html#cmdoption-c"><codeclass="xref std std-option docutils literal notranslate"><spanclass="pre">-c</span></code></a> option) is a code block.
A module run as a top level script (as module <codeclass="docutils literal notranslate"><spanclass="pre">__main__</span></code>) from the command
line using a <aclass="reference internal" href="../using/cmdline.html#cmdoption-m"><codeclass="xref std std-option docutils literal notranslate"><spanclass="pre">-m</span></code></a> argument is also a code block. The string
argument passed to the built-in functions <aclass="reference internal" href="../builtins/functions.html#eval" title="eval"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">eval()</span></code></a> and <aclass="reference internal" href="../builtins/functions.html#exec" title="exec"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">exec()</span></code></a> is a
code block.</p>
<pid="index-2">A code block is executed in an <emclass="dfn">execution frame</em>. A frame contains some
administrative information (used for debugging) and determines where and how
execution continues after the code block's execution has completed.</p>
</section>
<sectionid="naming-and-binding">
<spanid="naming"></span><h2><spanclass="section-number">4.2. </span>Naming and binding<aclass="headerlink" href="#naming-and-binding" title="連結到這個標頭">¶</a></h2>
<sectionid="binding-of-names">
<spanid="bind-names"></span><spanid="index-3"></span><h3><spanclass="section-number">4.2.1. </span>Binding of names<aclass="headerlink" href="#binding-of-names" title="連結到這個標頭">¶</a></h3>
<pid="index-4"><emclass="dfn">Names</em> refer to objects. Names are introduced by name binding operations.</p>
<pid="index-5">The following constructs bind names:</p>
<ulclass="simple">
<li><p>formal parameters to functions,</p></li>
<li><p>class definitions,</p></li>
<li><p>function definitions,</p></li>
<li><p>assignment expressions,</p></li>
<li><p><aclass="reference internal" href="simple_stmts.html#assignment"><spanclass="std std-ref">targets</span></a> that are identifiers if occurring in
clause, <aclass="reference internal" href="compound_stmts.html#except-star"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except*</span></code></a> clause, or in the as-pattern in structural pattern matching,</p></li>
<li><p>in a capture pattern in structural pattern matching</p></li>
<p>The <codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">import</span></code> statement of the form <codeclass="docutils literal notranslate"><spanclass="pre">from</span><spanclass="pre">...</span><spanclass="pre">import</span><spanclass="pre">*</span></code> binds all
names defined in the imported module, except those beginning with an underscore.
This form may only be used at the module level.</p>
<p>A target occurring in a <aclass="reference internal" href="simple_stmts.html#del"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">del</span></code></a> statement is also considered bound for
this purpose (though the actual semantics are to unbind the name).</p>
<p>Each assignment or import statement occurs within a block defined by a class or
function definition or at the module level (the top-level code block).</p>
<pid="index-6">If a name is bound in a block, it is a local variable of that block, unless
declared as <aclass="reference internal" href="simple_stmts.html#nonlocal"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">nonlocal</span></code></a> or <aclass="reference internal" href="simple_stmts.html#global"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">global</span></code></a>. If a name is bound at
the module level, it is a global variable. (The variables of the module code
block are local and global.) If a variable is used in a code block but not
defined there, it is a <aclass="reference internal" href="../glossary.html#term-free-variable"><spanclass="xref std std-term">free variable</span></a>.</p>
<p>Each occurrence of a name in the program text refers to the <emclass="dfn">binding</em> of
that name established by the following name resolution rules.</p>
</section>
<sectionid="resolution-of-names">
<spanid="resolve-names"></span><h3><spanclass="section-number">4.2.2. </span>Resolution of names<aclass="headerlink" href="#resolution-of-names" title="連結到這個標頭">¶</a></h3>
<pid="index-7">A <emclass="dfn">scope</em> defines the visibility of a name within a block. If a local
variable is defined in a block, its scope includes that block. If the
definition occurs in a function block, the scope extends to any blocks contained
within the defining one, unless a contained block introduces a different binding
for the name.</p>
<pid="index-8">When a name is used in a code block, it is resolved using the nearest enclosing
scope. The set of all such scopes visible to a code block is called the block's
<emclass="dfn">environment</em>.</p>
<pid="index-9">When a name is not found at all, a <aclass="reference internal" href="../builtins/exceptions.html#NameError" title="NameError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">NameError</span></code></a> exception is raised.
If the current scope is a function scope, and the name refers to a local
variable that has not yet been bound to a value at the point where the name is
used, an <aclass="reference internal" href="../builtins/exceptions.html#UnboundLocalError" title="UnboundLocalError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">UnboundLocalError</span></code></a> exception is raised.
<aclass="reference internal" href="../builtins/exceptions.html#UnboundLocalError" title="UnboundLocalError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">UnboundLocalError</span></code></a> is a subclass of <aclass="reference internal" href="../builtins/exceptions.html#NameError" title="NameError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">NameError</span></code></a>.</p>
<p>If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block. This can
lead to errors when a name is used within a block before it is bound. This rule
is subtle. Python lacks declarations and allows name binding operations to
occur anywhere within a code block. The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.
See <aclass="reference internal" href="../faq/programming.html#faq-unboundlocalerror"><spanclass="std std-ref">the FAQ entry on UnboundLocalError</span></a>
for examples.</p>
<p>If the <aclass="reference internal" href="simple_stmts.html#global"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">global</span></code></a> statement occurs within a block, all uses of the names
specified in the statement refer to the bindings of those names in the top-level
namespace. Names are resolved in the top-level namespace by searching the
global namespace, i.e. the namespace of the module containing the code block,
and the builtins namespace, the namespace of the module <aclass="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">builtins</span></code></a>. The
global namespace is searched first. If the names are not found there, the
builtins namespace is searched next. If the names are also not found in the
builtins namespace, new variables are created in the global namespace.
The global statement must precede all uses of the listed names.</p>
<p>The <aclass="reference internal" href="simple_stmts.html#global"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">global</span></code></a> statement has the same scope as a name binding operation
in the same block. If the nearest enclosing scope for a free variable contains
a global statement, the free variable is treated as a global.</p>
to previously bound variables in the nearest enclosing function scope.
<aclass="reference internal" href="../builtins/exceptions.html#SyntaxError" title="SyntaxError"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">SyntaxError</span></code></a> is raised at compile time if the given name does not
exist in any enclosing function scope. <aclass="reference internal" href="compound_stmts.html#type-params"><spanclass="std std-ref">Type parameters</span></a>
cannot be rebound with the <codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">nonlocal</span></code> statement.</p>
<pid="index-10">The namespace for a module is automatically created the first time a module is
imported. The main module for a script is always called <aclass="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">__main__</span></code></a>.</p>
<p>Class definition blocks and arguments to <aclass="reference internal" href="../builtins/functions.html#exec" title="exec"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">exec()</span></code></a> and <aclass="reference internal" href="../builtins/functions.html#eval" title="eval"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">eval()</span></code></a> are
special in the context of name resolution.
A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution with an exception
that unbound local variables are looked up in the global namespace.
The namespace of the class definition becomes the attribute dictionary of
the class. The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods. This includes
comprehensions and generator expressions, but it does not include
<li><p>Type parameter lists for <aclass="reference internal" href="compound_stmts.html#generic-type-aliases"><spanclass="std std-ref">generic type aliases</span></a>.</p></li>
<li><p>Type parameter lists for <aclass="reference internal" href="compound_stmts.html#generic-functions"><spanclass="std std-ref">generic functions</span></a>.
A generic function's annotations are
executed within the annotation scope, but its defaults and decorators are not.</p></li>
<li><p>Type parameter lists for <aclass="reference internal" href="compound_stmts.html#generic-classes"><spanclass="std std-ref">generic classes</span></a>.
A generic class's base classes and
keyword arguments are executed within the annotation scope, but its decorators are not.</p></li>
<li><p>The bounds, constraints, and default values for type parameters
expressions. (These expressions are allowed in other scopes contained within the
annotation scope.)</p></li>
<li><p>Names defined in annotation scopes cannot be rebound with <aclass="reference internal" href="simple_stmts.html#nonlocal"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">nonlocal</span></code></a>
statements in inner scopes. This includes only type parameters, as no other
syntactic elements that can appear within annotation scopes can introduce new names.</p></li>
<li><p>While annotation scopes have an internal name, that name is not reflected in the
<aclass="reference internal" href="../glossary.html#term-qualified-name"><spanclass="xref std std-term">qualified name</span></a> of objects defined within the scope.
of such objects is as if the object were defined in the enclosing scope.</p></li>
</ul>
<divclass="versionadded">
<p><spanclass="versionmodified added">在 3.12 版被加入: </span>Annotation scopes were introduced in Python 3.12 as part of <spanclass="target" id="index-11"></span><aclass="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.</p>
</div>
<divclass="versionchanged">
<p><spanclass="versionmodified changed">在 3.13 版的變更: </span>Annotation scopes are also used for type parameter defaults, as
introduced by <spanclass="target" id="index-12"></span><aclass="pep reference external" href="https://peps.python.org/pep-0696/"><strong>PEP 696</strong></a>.</p>
</div>
<divclass="versionchanged">
<p><spanclass="versionmodified changed">在 3.14 版的變更: </span>Annotation scopes are now also used for annotations, as specified in
<p>Most annotation scopes are <em>lazily evaluated</em>. This includes annotations,
the values of type aliases created through the <aclass="reference internal" href="simple_stmts.html#type"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">type</span></code></a> statement, and
the bounds, constraints, and default values of type
variables created through the <aclass="reference internal" href="compound_stmts.html#type-params"><spanclass="std std-ref">type parameter syntax</span></a>.
This means that they are not evaluated when the type alias or type variable is
created, or when the object carrying annotations is created. Instead, they
are only evaluated when necessary, for example when the <codeclass="docutils literal notranslate"><spanclass="pre">__value__</span></code>
<spanid="restrict-exec"></span><h3><spanclass="section-number">4.2.5. </span>Builtins and restricted execution<aclass="headerlink" href="#builtins-and-restricted-execution" title="連結到這個標頭">¶</a></h3>
<divclass="impl-detail compound" id="index-15">
<p><strong>CPython 實作細節:</strong> Users should not touch <codeclass="docutils literal notranslate"><spanclass="pre">__builtins__</span></code>; it is strictly an implementation
detail. Users wanting to override values in the builtins namespace should
<aclass="reference internal" href="simple_stmts.html#import"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">import</span></code></a> the <aclass="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">builtins</span></code></a> module and modify its
attributes appropriately.</p>
</div>
<p>The builtins namespace associated with the execution of a code block
is actually found by looking up the name <codeclass="docutils literal notranslate"><spanclass="pre">__builtins__</span></code> in its
global namespace; this should be a dictionary or a module (in the
latter case the module's dictionary is used). By default, when in the
<aclass="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">__main__</span></code></a> module, <codeclass="docutils literal notranslate"><spanclass="pre">__builtins__</span></code> is the built-in module
<aclass="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">builtins</span></code></a>; when in any other module, <codeclass="docutils literal notranslate"><spanclass="pre">__builtins__</span></code> is an
alias for the dictionary of the <aclass="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">builtins</span></code></a> module itself.</p>
</section>
<sectionid="interaction-with-dynamic-features">
<spanid="dynamic-features"></span><h3><spanclass="section-number">4.2.6. </span>Interaction with dynamic features<aclass="headerlink" href="#interaction-with-dynamic-features" title="連結到這個標頭">¶</a></h3>
<p>Name resolution of free variables occurs at runtime, not at compile time.
This means that the following code will print 42:</p>
<p>The <aclass="reference internal" href="../builtins/functions.html#eval" title="eval"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">eval()</span></code></a> and <aclass="reference internal" href="../builtins/functions.html#exec" title="exec"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">exec()</span></code></a> functions do not have access to the full
environment for resolving names. Names may be resolved in the local and global
namespaces of the caller. Free variables are not resolved in the nearest
enclosing namespace, but in the global namespace. <aclass="footnote-reference brackets" href="#id5" id="id3" role="doc-noteref"><spanclass="fn-bracket">[</span>1<spanclass="fn-bracket">]</span></a> The <aclass="reference internal" href="../builtins/functions.html#exec" title="exec"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">exec()</span></code></a> and
<aclass="reference internal" href="../builtins/functions.html#eval" title="eval"><codeclass="xref py py-func docutils literal notranslate"><spanclass="pre">eval()</span></code></a> functions have optional arguments to override the global and local
namespace. If only one namespace is specified, it is used for both.</p>
<pid="index-17"><spanid="index-16"></span>Exceptions are a means of breaking out of the normal flow of control of a code
block in order to handle errors or other exceptional conditions. An exception
is <em>raised</em> at the point where the error is detected; it may be <em>handled</em> by the
surrounding code block or by any code block that directly or indirectly invoked
the code block where the error occurred.</p>
<p>The Python interpreter raises an exception when it detects a run-time error
(such as division by zero). A Python program can also explicitly raise an
exception with the <aclass="reference internal" href="simple_stmts.html#raise"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> statement. Exception handlers are specified
with the <aclass="reference internal" href="compound_stmts.html#try"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> ... <aclass="reference internal" href="compound_stmts.html#except"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> statement. The <aclass="reference internal" href="compound_stmts.html#finally"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">finally</span></code></a>
clause of such a statement can be used to specify cleanup code which does not
handle the exception, but is executed whether an exception occurred or not in
the preceding code.</p>
<pid="index-18">Python uses the "termination" model of error handling: an exception handler can
find out what happened and continue execution at an outer level, but it cannot
repair the cause of the error and retry the failing operation (except by
re-entering the offending piece of code from the top).</p>
<pid="index-19">When an exception is not handled at all, the interpreter terminates execution of
the program, or returns to its interactive main loop. In either case, it prints
a stack traceback, except when the exception is <aclass="reference internal" href="../builtins/exceptions.html#SystemExit" title="SystemExit"><codeclass="xref py py-exc docutils literal notranslate"><spanclass="pre">SystemExit</span></code></a>.</p>
<p>Exceptions are identified by class instances. The <aclass="reference internal" href="compound_stmts.html#except"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">except</span></code></a> clause is
selected depending on the class of the instance: it must reference the class of
the instance or a <aclass="reference internal" href="../glossary.html#term-abstract-base-class"><spanclass="xref std std-term">non-virtual base class</span></a> thereof.
The instance can be received by the handler and can carry additional information
about the exceptional condition.</p>
<divclass="admonition note">
<pclass="admonition-title">備註</p>
<p>Exception messages are not part of the Python API. Their contents may change
from one version of Python to the next without warning and should not be
relied on by code which will run under multiple versions of the interpreter.</p>
</div>
<p>See also the description of the <aclass="reference internal" href="compound_stmts.html#try"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">try</span></code></a> statement in section <aclass="reference internal" href="compound_stmts.html#try"><spanclass="std std-ref">try 陳述式</span></a>
and <aclass="reference internal" href="simple_stmts.html#raise"><codeclass="xref std std-keyword docutils literal notranslate"><spanclass="pre">raise</span></code></a> statement in section <aclass="reference internal" href="simple_stmts.html#raise"><spanclass="std std-ref">raise 陳述式</span></a>.</p>
<p>At the conceptual level: when a Python program starts, it looks exactly
like that diagram, with one of each. The runtime may grow to include
multiple interpreters, and each interpreter may grow to include
multiple thread states.</p>
<divclass="admonition note">
<pclass="admonition-title">備註</p>
<p>A Python implementation won't necessarily implement the runtime
layers distinctly or even concretely. The only exception is places
where distinct layers are directly specified or exposed to users,
like through the <aclass="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">threading</span></code></a> module.</p>
</div>
<divclass="admonition note">
<pclass="admonition-title">備註</p>
<p>The initial interpreter is typically called the "main" interpreter.
Some Python implementations, like CPython, assign special roles
to the main interpreter.</p>
<p>Likewise, the host thread where the runtime was initialized is known
as the "main" thread. It may be different from the process' initial
thread, though they are often the same. In some cases "main thread"
may be even more specific and refer to the initial thread state.
A Python runtime might assign specific responsibilities
to the main thread, such as handling signals.</p>
</div>
<p>As a whole, the Python runtime consists of the global runtime state,
interpreters, and thread states. The runtime ensures all that state
stays consistent over its lifetime, particularly when used with
multiple host threads.</p>
<p>The global runtime, at the conceptual level, is just a set of
interpreters. While those interpreters are otherwise isolated and
independent from one another, they may share some data or other
resources. The runtime is responsible for managing these global
resources safely. The actual nature and management of these resources
is implementation-specific. Ultimately, the external utility of the
global runtime is limited to managing interpreters.</p>
<p>In contrast, an "interpreter" is conceptually what we would normally
think of as the (full-featured) "Python runtime". When machine code
executing in a host thread interacts with the Python runtime, it calls
into Python in the context of a specific interpreter.</p>
<divclass="admonition note">
<pclass="admonition-title">備註</p>
<p>The term "interpreter" here is not the same as the "bytecode
interpreter", which is what regularly runs in threads, executing
compiled Python code.</p>
<p>In an ideal world, "Python runtime" would refer to what we currently
call "interpreter". However, it's been called "interpreter" at least
since introduced in 1997 (<aclass="reference external" href="https://github.com/python/cpython/commit/a027efa5b">CPython:a027efa5b</a>).</p>
</div>
<p>Each interpreter completely encapsulates all of the non-process-global,
non-thread-specific state needed for the Python runtime to work.
Notably, the interpreter's state persists between uses. It includes
fundamental data like <aclass="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><codeclass="xref py py-data docutils literal notranslate"><spanclass="pre">sys.modules</span></code></a>. The runtime ensures
multiple threads using the same interpreter will safely
share it between them.</p>
<p>A Python implementation may support using multiple interpreters at the
same time in the same process. They are independent and isolated from
one another. For example, each interpreter has its own
<p>For thread-specific runtime state, each interpreter has a set of thread
states, which it manages, in the same way the global runtime contains
a set of interpreters. It can have thread states for as many host
threads as it needs. It may even have multiple thread states for
the same host thread, though that isn't as common.</p>
<p>Each thread state, conceptually, has all the thread-specific runtime
data an interpreter needs to operate in one host thread. The thread
state includes the current raised exception and the thread's Python
call stack. It may include other thread-specific resources.</p>
<divclass="admonition note">
<pclass="admonition-title">備註</p>
<p>The term "Python thread" can sometimes refer to a thread state, but
normally it means a thread created using the <aclass="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">threading</span></code></a> module.</p>
</div>
<p>Each thread state, over its lifetime, is always tied to exactly one
interpreter and exactly one host thread. It will only ever be used in
that thread and with that interpreter.</p>
<p>Multiple thread states may be tied to the same host thread, whether for
different interpreters or even the same interpreter. However, for any
given host thread, only one of the thread states tied to it can be used
by the thread at a time.</p>
<p>Thread states are isolated and independent from one another and don't
share any data, except for possibly sharing an interpreter and objects
or other resources belonging to that interpreter.</p>
<p>Once a program is running, new Python threads can be created using the
<aclass="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">threading</span></code></a> module (on platforms and Python implementations that
support threads). Additional processes can be created using the
<aclass="reference internal" href="../library/concurrent.interpreters.html#module-concurrent.interpreters" title="concurrent.interpreters: Multiple interpreters in the same process"><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">interpreters</span></code></a> module. Coroutines (async) can
be run using <aclass="reference internal" href="../library/asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><codeclass="xref py py-mod docutils literal notranslate"><spanclass="pre">asyncio</span></code></a> in each interpreter, typically only