Namespace confusion

Remco Gerlich scarblac at pino.selwerd.nl
Fri May 11 10:12:40 EDT 2001


Daniel Klein <danielk at aracnet.com> wrote in comp.lang.python:
> 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?

There is no truly global namespace, each module has its own global
namespace. So the interpreter has one, and so has the module ktest.

You won't find instances that aren't globals either, like local variables,
or if one is stored in a list, etc. This isn't the way to do this.

Depending on what you'd need it for, there are some other methods, like
keeping track of the amount of instances in some variable that the __init__
can increase, or keeping a list of instances (or one with weak refs), or if
you need a singleton, some other method, there are several.

-- 
Remco Gerlich



More information about the Python-list mailing list