Newcomer question wrt variable scope/namespaces
Gary Duzan
gary.duzan at motorola.com
Tue Jan 17 09:38:51 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 rule has to do with modifying namespaces. Setting a variable to
a value modifies the variable's binding in its namespace; it doesn't
matter whether the variable references a mutable or immutable type:
=========================================================================
$ python
Python 2.4.1 (#1, May 27 2005, 18:02:40)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = [1,2,3]
>>> def foo():
... a = 9
...
>>> def bar():
... b = [7,8,9]
...
>>> foo()
>>> print a
1
>>> bar()
>>> b
[1, 2, 3]
>>>
=========================================================================
Note that there is no error, but the binding affect each function's
local namespace instead of the global one. However, modifying a mutable
type, in this case a list, is not a namespace binding operation, i.e.,
it doesn't make the variable point to a different object. Since you only
need to access a variable's contents to modify the object to which it
refers, you can do this:
=========================================================================
>>> def blah():
... b[2] = 6
...
>>> blah()
>>> b
[1, 2, 6]
>>>
=========================================================================
It is easy to think that the scoping rules give you read-only behavior,
but with mutable objects it just isn't correct.
Gary Duzan
Motorola CHS
More information about the Python-list
mailing list