Namespace confusion

Daniel Klein danielk at aracnet.com
Fri May 11 09:12:35 EDT 2001


In an attempt to determine if an instance of a particular class already exists,
the following (interactive) code produces the desired result by checking the
global namespace:

>>> class K:
	def __init__(self):
		for obj in globals().values():
			if isinstance(obj,K):
				print 'found one'

				
>>> obj1 = K()
>>> obj2 = K()
found one

However, when I put this same code in a module, I get a different result, i.e.
no 'found one' message...

ktest.py
class K:
	def __init__(self):
		for obj in globals().values():
			if isinstance(obj,K):
				print 'found one'


>>> from ktest import K				
>>> obj1 = K()
>>> obj2 = K()

When I check globals() at the interactive prompt, my instances are indeedy
there. What's going on here?

Thanks,
Daniel Klein



More information about the Python-list mailing list