4. Modelo de Execussão
**********************


4.1. Estrutura de um programa
=============================

Um programa Python é construído a partir de blocos de código. Um
*bloco* é um pedaço do texto do programa Python que é executado como
uma unidade. A seguir estão os blocos: um módulo, um corpo de função e
uma definição de classe. Cada comando digitado interativamente é um
bloco. Um arquivo de script (um arquivo fornecido como entrada padrão
para o interpretador ou especificado como argumento de linha de
comando para o interpretador) é um bloco de código. Um comando de
script (um comando especificado na linha de comando do interpretador
com a opção "-c") é um bloco de código. O argumento da string passado
para as funções embutidas "eval()" e "exec()" é um bloco de código.

Um bloco de código é executado em um *quadro de execução*. Um quadro
contém algumas informações administrativas (usadas para depuração) e
determina onde e como a execução continua após a conclusão do bloco de
código.


4.2. Nomeação e ligação
=======================


4.2.1. Ligação de nomes
-----------------------

*Nomes* referem-se a objetos. Os nomes são introduzidos por operações
de ligação de nomes.

The following constructs bind names: formal parameters to functions,
"import" statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are
identifiers if occurring in an assignment, "for" loop header, or after
"as" in a "with" statement or "except" clause. The "import" statement
of the form "from ... import *" binds all names defined in the
imported module, except those beginning with an underscore.  This form
may only be used at the module level.

Um alvo ocorrendo em uma instrução "del" também é considerado ligado a
esse propósito (embora a semântica real seja para desligar do nome).

Cada atribuição ou instrução de importação ocorre dentro de um bloco
definido por uma definição de classe ou função ou no nível do módulo
(o bloco de código de nível superior).

Se um nome está ligado a um bloco, é uma variável local desse bloco, a
menos que declarado como "nonlocal" ou "global". Se um nome está
ligado a nível do módulo, é uma variável global. (As variáveis ​​do
bloco de código do módulo são locais e globais.) Se uma variável for
usada em um bloco de código, mas não definida lá, é uma *variável
livre*.

Cada ocorrência de um nome no texto do programa se refere à *ligação*
daquele nome estabelecido pelas seguintes regras de resolução de nome.


4.2.2. Resolução de nomes
-------------------------

O *escopo* define a visibilidade de um nome dentro de um bloco. Se uma
variável local é definida em um bloco, seu escopo inclui esse bloco.
Se a definição ocorrer em um bloco de função, o escopo se estende a
quaisquer blocos contidos no bloco de definição, a menos que um bloco
contido introduza uma ligação diferente para o nome.

Quando um nome é usado em um bloco de código, ele é resolvido usando o
escopo envolvente mais próximo. O conjunto de todos esses escopos
visíveis a um bloco de código é chamado de *ambiente* do bloco.

Quando um nome não é encontrado, uma exceção "NameError" é levantada.
Se o escopo atual for um escopo de função e o nome se referir a uma
variável local que ainda não foi associada a um valor no ponto onde o
nome é usado, uma exceção "UnboundLocalError" é levantada.
"UnboundLocalError" é uma subclasse de "NameError".

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.

If the "global" statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name 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 "builtins".  The global namespace is searched first.  If
the name is not found there, the builtins namespace is searched.  The
"global" statement must precede all uses of the name.

The "global" 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.

The "nonlocal" statement causes corresponding names to refer to
previously bound variables in the nearest enclosing function scope.
"SyntaxError" is raised at compile time if the given name does not
exist in any enclosing function scope.

The namespace for a module is automatically created the first time a
module is imported.  The main module for a script is always called
"__main__".

Class definition blocks and arguments to "exec()" and "eval()" 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 since they are
implemented using a function scope.  This means that the following
will fail:

   class A:
       a = 42
       b = list(a + i for i in range(10))


4.2.3. Builtins and restricted execution
----------------------------------------

**CPython implementation detail:** Users should not touch
"__builtins__"; it is strictly an implementation detail.  Users
wanting to override values in the builtins namespace should "import"
the "builtins" module and modify its attributes appropriately.

The builtins namespace associated with the execution of a code block
is actually found by looking up the name "__builtins__" 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 "__main__"
module, "__builtins__" is the built-in module "builtins"; when in any
other module, "__builtins__" is an alias for the dictionary of the
"builtins" module itself.


4.2.4. Interaction with dynamic features
----------------------------------------

Name resolution of free variables occurs at runtime, not at compile
time. This means that the following code will print 42:

   i = 10
   def f():
       print(i)
   i = 42
   f()

The "eval()" and "exec()" 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.  [1]
The "exec()" and "eval()" functions have optional arguments to
override the global and local namespace.  If only one namespace is
specified, it is used for both.


4.3. Exceções
=============

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 *raised* at the point where the error is
detected; it may be *handled* by the surrounding code block or by any
code block that directly or indirectly invoked the code block where
the error occurred.

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 "raise" statement. Exception
handlers are specified with the "try" ... "except" statement.  The
"finally" 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.

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).

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 backtrace, except when the exception is
"SystemExit".

Exceptions are identified by class instances.  The "except" clause is
selected depending on the class of the instance: it must reference the
class of the instance or a base class thereof.  The instance can be
received by the handler and can carry additional information about the
exceptional condition.

Nota:

  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.

See also the description of the "try" statement in section The try
statement and "raise" statement in section The raise statement.

-[ Notas de Rodapé ]-

[1] This limitation occurs because the code that is executed by these
    operations is not available at the time the module is compiled.
