newbie - Scoping question

T.Meyarivan mary at iitk.ac.in
Mon Sep 17 19:11:49 CEST 2001


> ----- python interactive session begin ----
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> import test
> >>> from test import *
> >>> dir(test)
> ['__builtins__', '__doc__', '__file__', '__name__', 'get_x', 'set_x',
> 'x']
> >>> x = [1,2,3]

when you assign [1, 2, 3] to x, you are no longer referring to the
'variable' x imported from test but a new local variable. you can
print the id of the 'variable' x before and after the assignment to
see the change.

Python 2.2a1 (#1, Aug  8 2001, 22:01:10)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> from test import *
>>> id(x)
135516044  ## the id of the variable x defined in module test
>>> get_x()
[]
>>> x = range(3)
>>> id(x)
135518932  ## the variable x no longer refers to that defined in the module
>>> get_x()
[]
>>> from test import *
>>> id(x)
135516044
>>> x.append(range(3))
>>> id(x)
135516044
>>> get_x()
[[0, 1, 2]]
>>>

mary






More information about the Python-list mailing list