Is an interactive command a block?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Nov 19 16:08:15 EST 2009


On Thu, 19 Nov 2009 21:37:17 +0100, Alf P. Steinbach wrote:

> The CPython 3.1.1 language reference §4.1 says
> 
>    "Each command typed interactively is a block."
> 
> It also says
> 
>    "If a name is bound in a block, it is a local variable of that block,
>    unless
>     declared as nonlocal"
> 
> Even with a non-literal try-for-best-meaning reading I can't get this to
> mesh with the actual behavior of the interpreter, e.g.
> 
>    >>> for x in "poi":
>    ...    fandango = 666
>    ...
>    >>> fandango
>    666
>    >>> _
> 
> My current understanding is (A) that the interpreter is correct in this
> respect (for one would harldly want the effects of statements to be
> fundamentally different in interpreted mode, except the presentation of
> expression results), and (B), but here I'm less sure, that the
> documentation is incorrect.


Why do you say that? I don't see what it is in the command you typed that 
leads you to think the documentation is incorrect.

The first command you type is:

for x in "poi":
    fandango = 666


which binds two names, x and fandango. Since you are not typing them in a 
function or class definition, locals() is globals() and the two local 
names you create happen to also be globals.

The next two commands you type:

fandango
_

don't bind anything, so aren't relevant.

If it helps:


>>> for x in "poi":
...     fandango = 666
...
>>> locals() is globals()
True
>>> fandango
666
>>> locals()['fandango']
666
>>> import __main__
>>> __main__.fandango
666



-- 
Steven



More information about the Python-list mailing list