[BangPypers] Enclosing lexical context

Anand Balachandran Pillai abpillai at gmail.com
Thu Apr 15 19:54:05 CEST 2010


My reply got deleted partly before I sent it. Here is the full one.

It is not clear from your email what context means but mostly it
is the fact that Python differentiates between local and global
scope when variables are assigned.

For example,

>>> a=10
>>> def f(x):
...     a=x
...     print a
...
>>> f(20)
20
>>> print a
10

The global "a" is still unmodified since the f() function changes only
its local a. To "fix" this we need to prefix the local a with "global".

>>> def f(x):
...     global a
...     a=x
...     print a
...
>>> f(20)
20
>>> print a
20

However, this can also be done using a container as below.

>>> a=[10]
>>> def f(x):
...     a[0]=x
...     print a
...
>>> f(2)
[2]
>>> print a
[2]

In this case, the outer a is accessed automatically since we are using
indices and there is no  local list "a", Python finds the scope from
the global scope and assigns correctly.

Looking at your code above, perhaps the 2nd explanation
makes it clearer and seems closer to what you are expecting
as answer.

--Anand



On Thu, Apr 15, 2010 at 11:19 PM, Anand Balachandran Pillai <
abpillai at gmail.com> wrote:

>
>
> On Thu, Apr 15, 2010 at 10:36 PM, Picachu Nioto <picachu.nioto at gmail.com>wrote:
>
>> Could some one explain to me this sentence, I read in an example online
>>
>> "Python doesn't implement assignment of variables bound in an enclosing
>> lexical context"
>>
> >>> a=[10]
> >>> def f(x):
> ...     a[0]=x
> ...     print a
> ...
> >>> f(2)
> [2]
> >>> print a
> [2]
>
> In this case, the outer a is accessed automatically since we are using
> indices and there is no  local list "a", Python finds the scope from
> the global scope and assigns correctly.
>
>
>> Example,
>> a=[b]
>>
>>
> Looking at your code above, perhaps the 2nd explanation
> makes it clear.
>
>
>> --Picachu
>> _______________________________________________
>> BangPypers mailing list
>> BangPypers at python.org
>> http://mail.python.org/mailman/listinfo/bangpypers
>>
>
>
>
> --
> --Anand
>
>
>
>


-- 
--Anand


More information about the BangPypers mailing list