Newcomer question wrt variable scope/namespaces

Diez B. Roggisch deets at nospam.web.de
Sat Jan 14 14:10:07 EST 2006


Florian Daniel Otel wrote:
> Gary,
> 
> First of all, many  thanks for the reply. Do I understand it correctly
> that actually the rule has to be refined as pertaining  to the (so
> called) "immutable" types (like e.g.  integers, tuples/strings)
> whereas lists and dictionaries are "mutable" types and the said
> scoping rule does not apply ?

The scoping rules _do_ apply in all circumstances - they forbid changing 
the binding of a name to an _object_.

So (without any scoping whatsoever):

 >>> a = 1
 >>> b = []
 >>> id(a)
2000000
 >>> id(b)
3000000

there is no way you can change the value of the object with id 2000000, 
which the name a points to. Because it is immutable, which tuples are, too.

But on the list with id 3000000 you can invoke some methods that mutate it.

The scoping has _nothing_ to do with these facts. But in case of a 
closure, the operation

b = 1

is forbidden, as it tries to rebind the name b to another object. 
Similar, the scoping rules in case of global variables without 
global-declaration allow access to the global through its name, but 
prevent the global name being rebound to another value - instead, 
silently a local name is created.

Regards,

Diez



More information about the Python-list mailing list