newbie - Scoping question

Mark Jackson mjackson at wrc.xerox.com
Mon Sep 17 12:11:41 EDT 2001


padhia at yahoo.com (P Adhia) writes:

> Consider following code in modlue test.py
> 
> ----- code begin ----
> """Module test.py"""
> 
> x = []
> 
> def get_x():
> 	print x
> 
> def set_x(default):
> 	global x
> 	x = default
> ----- code end ----
> 
> now I am trying to set value of "x" interactively as,
> 
> ----- 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 *

The top-level namespace now contains the names get_x, set_x, and x,
which refer to the same objects as the corresponding names in module test.

> >>> dir(test)
> ['__builtins__', '__doc__', '__file__', '__name__', 'get_x', 'set_x',
> 'x']
> >>> x = [1,2,3]

You have just rebound x to a new list object, which has no relation at
all to test.x.

> >>> x
> [1, 2, 3]
> >>> get_x()
> []

Yep, two different objects.

> >>> test.x = [4,5,6]

You have just rebound test.x to yet another new list object.

> >>> get_x()
> [4, 5, 6]
> >>> x
> [1, 2, 3]

Yep, two different objects.

> >>>
> ----- python interactive session end ----
> 
> I am confused as to why "x", when not qualified with module name, does
> not refer to "x" in "test", even though I did "from test import *".

You need to reread the documentation pertaining to namespaces, import,
and what "from import" actually does.

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
	Physics is like sex:  sure, it may give some practical results,
	but that's not why we do it.	- Richard Feynman





More information about the Python-list mailing list