17db96d56Sopenharmony_ci
27db96d56Sopenharmony_ci.. _execmodel:
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci***************
57db96d56Sopenharmony_ciExecution model
67db96d56Sopenharmony_ci***************
77db96d56Sopenharmony_ci
87db96d56Sopenharmony_ci.. index::
97db96d56Sopenharmony_ci   single: execution model
107db96d56Sopenharmony_ci   pair: code; block
117db96d56Sopenharmony_ci
127db96d56Sopenharmony_ci.. _prog_structure:
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ciStructure of a program
157db96d56Sopenharmony_ci======================
167db96d56Sopenharmony_ci
177db96d56Sopenharmony_ci.. index:: block
187db96d56Sopenharmony_ci
197db96d56Sopenharmony_ciA Python program is constructed from code blocks.
207db96d56Sopenharmony_ciA :dfn:`block` is a piece of Python program text that is executed as a unit.
217db96d56Sopenharmony_ciThe following are blocks: a module, a function body, and a class definition.
227db96d56Sopenharmony_ciEach command typed interactively is a block.  A script file (a file given as
237db96d56Sopenharmony_cistandard input to the interpreter or specified as a command line argument to the
247db96d56Sopenharmony_ciinterpreter) is a code block.  A script command (a command specified on the
257db96d56Sopenharmony_ciinterpreter command line with the :option:`-c` option) is a code block.
267db96d56Sopenharmony_ciA module run as a top level script (as module ``__main__``) from the command
277db96d56Sopenharmony_ciline using a :option:`-m` argument is also a code block. The string
287db96d56Sopenharmony_ciargument passed to the built-in functions :func:`eval` and :func:`exec` is a
297db96d56Sopenharmony_cicode block.
307db96d56Sopenharmony_ci
317db96d56Sopenharmony_ci.. index:: pair: execution; frame
327db96d56Sopenharmony_ci
337db96d56Sopenharmony_ciA code block is executed in an :dfn:`execution frame`.  A frame contains some
347db96d56Sopenharmony_ciadministrative information (used for debugging) and determines where and how
357db96d56Sopenharmony_ciexecution continues after the code block's execution has completed.
367db96d56Sopenharmony_ci
377db96d56Sopenharmony_ci.. _naming:
387db96d56Sopenharmony_ci
397db96d56Sopenharmony_ciNaming and binding
407db96d56Sopenharmony_ci==================
417db96d56Sopenharmony_ci
427db96d56Sopenharmony_ci.. index::
437db96d56Sopenharmony_ci   single: namespace
447db96d56Sopenharmony_ci   single: scope
457db96d56Sopenharmony_ci
467db96d56Sopenharmony_ci.. _bind_names:
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ciBinding of names
497db96d56Sopenharmony_ci----------------
507db96d56Sopenharmony_ci
517db96d56Sopenharmony_ci.. index::
527db96d56Sopenharmony_ci   single: name
537db96d56Sopenharmony_ci   pair: binding; name
547db96d56Sopenharmony_ci
557db96d56Sopenharmony_ci:dfn:`Names` refer to objects.  Names are introduced by name binding operations.
567db96d56Sopenharmony_ci
577db96d56Sopenharmony_ci.. index:: single: from; import statement
587db96d56Sopenharmony_ci
597db96d56Sopenharmony_ciThe following constructs bind names:
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ci* formal parameters to functions,
627db96d56Sopenharmony_ci* class definitions,
637db96d56Sopenharmony_ci* function definitions,
647db96d56Sopenharmony_ci* assignment expressions,
657db96d56Sopenharmony_ci* :ref:`targets <assignment>` that are identifiers if occurring in
667db96d56Sopenharmony_ci  an assignment:
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ci  + :keyword:`for` loop header,
697db96d56Sopenharmony_ci  + after :keyword:`!as` in a :keyword:`with` statement, :keyword:`except`
707db96d56Sopenharmony_ci    clause, :keyword:`except* <except_star>` clause, or in the as-pattern in structural pattern matching,
717db96d56Sopenharmony_ci  + in a capture pattern in structural pattern matching
727db96d56Sopenharmony_ci
737db96d56Sopenharmony_ci* :keyword:`import` statements.
747db96d56Sopenharmony_ci
757db96d56Sopenharmony_ciThe :keyword:`!import` statement of the form ``from ... import *`` binds all
767db96d56Sopenharmony_cinames defined in the imported module, except those beginning with an underscore.
777db96d56Sopenharmony_ciThis form may only be used at the module level.
787db96d56Sopenharmony_ci
797db96d56Sopenharmony_ciA target occurring in a :keyword:`del` statement is also considered bound for
807db96d56Sopenharmony_cithis purpose (though the actual semantics are to unbind the name).
817db96d56Sopenharmony_ci
827db96d56Sopenharmony_ciEach assignment or import statement occurs within a block defined by a class or
837db96d56Sopenharmony_cifunction definition or at the module level (the top-level code block).
847db96d56Sopenharmony_ci
857db96d56Sopenharmony_ci.. index:: pair: free; variable
867db96d56Sopenharmony_ci
877db96d56Sopenharmony_ciIf a name is bound in a block, it is a local variable of that block, unless
887db96d56Sopenharmony_cideclared as :keyword:`nonlocal` or :keyword:`global`.  If a name is bound at
897db96d56Sopenharmony_cithe module level, it is a global variable.  (The variables of the module code
907db96d56Sopenharmony_ciblock are local and global.)  If a variable is used in a code block but not
917db96d56Sopenharmony_cidefined there, it is a :dfn:`free variable`.
927db96d56Sopenharmony_ci
937db96d56Sopenharmony_ciEach occurrence of a name in the program text refers to the :dfn:`binding` of
947db96d56Sopenharmony_cithat name established by the following name resolution rules.
957db96d56Sopenharmony_ci
967db96d56Sopenharmony_ci.. _resolve_names:
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ciResolution of names
997db96d56Sopenharmony_ci-------------------
1007db96d56Sopenharmony_ci
1017db96d56Sopenharmony_ci.. index:: scope
1027db96d56Sopenharmony_ci
1037db96d56Sopenharmony_ciA :dfn:`scope` defines the visibility of a name within a block.  If a local
1047db96d56Sopenharmony_civariable is defined in a block, its scope includes that block.  If the
1057db96d56Sopenharmony_cidefinition occurs in a function block, the scope extends to any blocks contained
1067db96d56Sopenharmony_ciwithin the defining one, unless a contained block introduces a different binding
1077db96d56Sopenharmony_cifor the name.
1087db96d56Sopenharmony_ci
1097db96d56Sopenharmony_ci.. index:: single: environment
1107db96d56Sopenharmony_ci
1117db96d56Sopenharmony_ciWhen a name is used in a code block, it is resolved using the nearest enclosing
1127db96d56Sopenharmony_ciscope.  The set of all such scopes visible to a code block is called the block's
1137db96d56Sopenharmony_ci:dfn:`environment`.
1147db96d56Sopenharmony_ci
1157db96d56Sopenharmony_ci.. index::
1167db96d56Sopenharmony_ci   single: NameError (built-in exception)
1177db96d56Sopenharmony_ci   single: UnboundLocalError
1187db96d56Sopenharmony_ci
1197db96d56Sopenharmony_ciWhen a name is not found at all, a :exc:`NameError` exception is raised.
1207db96d56Sopenharmony_ciIf the current scope is a function scope, and the name refers to a local
1217db96d56Sopenharmony_civariable that has not yet been bound to a value at the point where the name is
1227db96d56Sopenharmony_ciused, an :exc:`UnboundLocalError` exception is raised.
1237db96d56Sopenharmony_ci:exc:`UnboundLocalError` is a subclass of :exc:`NameError`.
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ciIf a name binding operation occurs anywhere within a code block, all uses of the
1267db96d56Sopenharmony_ciname within the block are treated as references to the current block.  This can
1277db96d56Sopenharmony_cilead to errors when a name is used within a block before it is bound.  This rule
1287db96d56Sopenharmony_ciis subtle.  Python lacks declarations and allows name binding operations to
1297db96d56Sopenharmony_cioccur anywhere within a code block.  The local variables of a code block can be
1307db96d56Sopenharmony_cidetermined by scanning the entire text of the block for name binding operations.
1317db96d56Sopenharmony_ciSee :ref:`the FAQ entry on UnboundLocalError <faq-unboundlocalerror>`
1327db96d56Sopenharmony_cifor examples.
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ciIf the :keyword:`global` statement occurs within a block, all uses of the names
1357db96d56Sopenharmony_cispecified in the statement refer to the bindings of those names in the top-level
1367db96d56Sopenharmony_cinamespace.  Names are resolved in the top-level namespace by searching the
1377db96d56Sopenharmony_ciglobal namespace, i.e. the namespace of the module containing the code block,
1387db96d56Sopenharmony_ciand the builtins namespace, the namespace of the module :mod:`builtins`.  The
1397db96d56Sopenharmony_ciglobal namespace is searched first.  If the names are not found there, the
1407db96d56Sopenharmony_cibuiltins namespace is searched.  The :keyword:`!global` statement must precede
1417db96d56Sopenharmony_ciall uses of the listed names.
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ciThe :keyword:`global` statement has the same scope as a name binding operation
1447db96d56Sopenharmony_ciin the same block.  If the nearest enclosing scope for a free variable contains
1457db96d56Sopenharmony_cia global statement, the free variable is treated as a global.
1467db96d56Sopenharmony_ci
1477db96d56Sopenharmony_ci.. XXX say more about "nonlocal" semantics here
1487db96d56Sopenharmony_ci
1497db96d56Sopenharmony_ciThe :keyword:`nonlocal` statement causes corresponding names to refer
1507db96d56Sopenharmony_cito previously bound variables in the nearest enclosing function scope.
1517db96d56Sopenharmony_ci:exc:`SyntaxError` is raised at compile time if the given name does not
1527db96d56Sopenharmony_ciexist in any enclosing function scope.
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ci.. index:: pair: module; __main__
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ciThe namespace for a module is automatically created the first time a module is
1577db96d56Sopenharmony_ciimported.  The main module for a script is always called :mod:`__main__`.
1587db96d56Sopenharmony_ci
1597db96d56Sopenharmony_ciClass definition blocks and arguments to :func:`exec` and :func:`eval` are
1607db96d56Sopenharmony_cispecial in the context of name resolution.
1617db96d56Sopenharmony_ciA class definition is an executable statement that may use and define names.
1627db96d56Sopenharmony_ciThese references follow the normal rules for name resolution with an exception
1637db96d56Sopenharmony_cithat unbound local variables are looked up in the global namespace.
1647db96d56Sopenharmony_ciThe namespace of the class definition becomes the attribute dictionary of
1657db96d56Sopenharmony_cithe class. The scope of names defined in a class block is limited to the
1667db96d56Sopenharmony_ciclass block; it does not extend to the code blocks of methods -- this includes
1677db96d56Sopenharmony_cicomprehensions and generator expressions since they are implemented using a
1687db96d56Sopenharmony_cifunction scope.  This means that the following will fail::
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ci   class A:
1717db96d56Sopenharmony_ci       a = 42
1727db96d56Sopenharmony_ci       b = list(a + i for i in range(10))
1737db96d56Sopenharmony_ci
1747db96d56Sopenharmony_ci.. _restrict_exec:
1757db96d56Sopenharmony_ci
1767db96d56Sopenharmony_ciBuiltins and restricted execution
1777db96d56Sopenharmony_ci---------------------------------
1787db96d56Sopenharmony_ci
1797db96d56Sopenharmony_ci.. index:: pair: restricted; execution
1807db96d56Sopenharmony_ci
1817db96d56Sopenharmony_ci.. impl-detail::
1827db96d56Sopenharmony_ci
1837db96d56Sopenharmony_ci   Users should not touch ``__builtins__``; it is strictly an implementation
1847db96d56Sopenharmony_ci   detail.  Users wanting to override values in the builtins namespace should
1857db96d56Sopenharmony_ci   :keyword:`import` the :mod:`builtins` module and modify its
1867db96d56Sopenharmony_ci   attributes appropriately.
1877db96d56Sopenharmony_ci
1887db96d56Sopenharmony_ciThe builtins namespace associated with the execution of a code block
1897db96d56Sopenharmony_ciis actually found by looking up the name ``__builtins__`` in its
1907db96d56Sopenharmony_ciglobal namespace; this should be a dictionary or a module (in the
1917db96d56Sopenharmony_cilatter case the module's dictionary is used).  By default, when in the
1927db96d56Sopenharmony_ci:mod:`__main__` module, ``__builtins__`` is the built-in module
1937db96d56Sopenharmony_ci:mod:`builtins`; when in any other module, ``__builtins__`` is an
1947db96d56Sopenharmony_cialias for the dictionary of the :mod:`builtins` module itself.
1957db96d56Sopenharmony_ci
1967db96d56Sopenharmony_ci
1977db96d56Sopenharmony_ci.. _dynamic-features:
1987db96d56Sopenharmony_ci
1997db96d56Sopenharmony_ciInteraction with dynamic features
2007db96d56Sopenharmony_ci---------------------------------
2017db96d56Sopenharmony_ci
2027db96d56Sopenharmony_ciName resolution of free variables occurs at runtime, not at compile time.
2037db96d56Sopenharmony_ciThis means that the following code will print 42::
2047db96d56Sopenharmony_ci
2057db96d56Sopenharmony_ci   i = 10
2067db96d56Sopenharmony_ci   def f():
2077db96d56Sopenharmony_ci       print(i)
2087db96d56Sopenharmony_ci   i = 42
2097db96d56Sopenharmony_ci   f()
2107db96d56Sopenharmony_ci
2117db96d56Sopenharmony_ci.. XXX from * also invalid with relative imports (at least currently)
2127db96d56Sopenharmony_ci
2137db96d56Sopenharmony_ciThe :func:`eval` and :func:`exec` functions do not have access to the full
2147db96d56Sopenharmony_cienvironment for resolving names.  Names may be resolved in the local and global
2157db96d56Sopenharmony_cinamespaces of the caller.  Free variables are not resolved in the nearest
2167db96d56Sopenharmony_cienclosing namespace, but in the global namespace.  [#]_ The :func:`exec` and
2177db96d56Sopenharmony_ci:func:`eval` functions have optional arguments to override the global and local
2187db96d56Sopenharmony_cinamespace.  If only one namespace is specified, it is used for both.
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ci
2217db96d56Sopenharmony_ci.. _exceptions:
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ciExceptions
2247db96d56Sopenharmony_ci==========
2257db96d56Sopenharmony_ci
2267db96d56Sopenharmony_ci.. index:: single: exception
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ci.. index::
2297db96d56Sopenharmony_ci   single: raise an exception
2307db96d56Sopenharmony_ci   single: handle an exception
2317db96d56Sopenharmony_ci   single: exception handler
2327db96d56Sopenharmony_ci   single: errors
2337db96d56Sopenharmony_ci   single: error handling
2347db96d56Sopenharmony_ci
2357db96d56Sopenharmony_ciExceptions are a means of breaking out of the normal flow of control of a code
2367db96d56Sopenharmony_ciblock in order to handle errors or other exceptional conditions.  An exception
2377db96d56Sopenharmony_ciis *raised* at the point where the error is detected; it may be *handled* by the
2387db96d56Sopenharmony_cisurrounding code block or by any code block that directly or indirectly invoked
2397db96d56Sopenharmony_cithe code block where the error occurred.
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ciThe Python interpreter raises an exception when it detects a run-time error
2427db96d56Sopenharmony_ci(such as division by zero).  A Python program can also explicitly raise an
2437db96d56Sopenharmony_ciexception with the :keyword:`raise` statement. Exception handlers are specified
2447db96d56Sopenharmony_ciwith the :keyword:`try` ... :keyword:`except` statement.  The :keyword:`finally`
2457db96d56Sopenharmony_ciclause of such a statement can be used to specify cleanup code which does not
2467db96d56Sopenharmony_cihandle the exception, but is executed whether an exception occurred or not in
2477db96d56Sopenharmony_cithe preceding code.
2487db96d56Sopenharmony_ci
2497db96d56Sopenharmony_ci.. index:: single: termination model
2507db96d56Sopenharmony_ci
2517db96d56Sopenharmony_ciPython uses the "termination" model of error handling: an exception handler can
2527db96d56Sopenharmony_cifind out what happened and continue execution at an outer level, but it cannot
2537db96d56Sopenharmony_cirepair the cause of the error and retry the failing operation (except by
2547db96d56Sopenharmony_cire-entering the offending piece of code from the top).
2557db96d56Sopenharmony_ci
2567db96d56Sopenharmony_ci.. index:: single: SystemExit (built-in exception)
2577db96d56Sopenharmony_ci
2587db96d56Sopenharmony_ciWhen an exception is not handled at all, the interpreter terminates execution of
2597db96d56Sopenharmony_cithe program, or returns to its interactive main loop.  In either case, it prints
2607db96d56Sopenharmony_cia stack traceback, except when the exception is :exc:`SystemExit`.
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_ciExceptions are identified by class instances.  The :keyword:`except` clause is
2637db96d56Sopenharmony_ciselected depending on the class of the instance: it must reference the class of
2647db96d56Sopenharmony_cithe instance or a :term:`non-virtual base class <abstract base class>` thereof.
2657db96d56Sopenharmony_ciThe instance can be received by the handler and can carry additional information
2667db96d56Sopenharmony_ciabout the exceptional condition.
2677db96d56Sopenharmony_ci
2687db96d56Sopenharmony_ci.. note::
2697db96d56Sopenharmony_ci
2707db96d56Sopenharmony_ci   Exception messages are not part of the Python API.  Their contents may change
2717db96d56Sopenharmony_ci   from one version of Python to the next without warning and should not be
2727db96d56Sopenharmony_ci   relied on by code which will run under multiple versions of the interpreter.
2737db96d56Sopenharmony_ci
2747db96d56Sopenharmony_ciSee also the description of the :keyword:`try` statement in section :ref:`try`
2757db96d56Sopenharmony_ciand :keyword:`raise` statement in section :ref:`raise`.
2767db96d56Sopenharmony_ci
2777db96d56Sopenharmony_ci
2787db96d56Sopenharmony_ci.. rubric:: Footnotes
2797db96d56Sopenharmony_ci
2807db96d56Sopenharmony_ci.. [#] This limitation occurs because the code that is executed by these operations
2817db96d56Sopenharmony_ci       is not available at the time the module is compiled.
282