Namespace confusion

Alex Martelli aleaxit at yahoo.com
Fri May 11 09:51:19 EDT 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:hionftslb6s0auidrv58rnpprg06ins4cb at 4ax.com...
> 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'

This doesn't tell you whether any instance of K "exists": it
tells you whether one is bound to a global variable in the
same module where class K is defined.  It doesn't check many
other places where a reference to an instance of class K might
be stashed away -- including local variables of functions that
are active, items and attributes of other objects, etc.

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

Try this...:
>>> obj1 = [K()]
>>> obj2 = [K()]
>>>

the second __init__ won't find the first instance because it's
not bound to obj1, but rather to obj1[0] -- just one of the
many possibilities that aren't being searched.

If K does need to keep track of all of its instances it had
better keep a list of them as it generates them.  See the
weakref module in Python 2.1 -- a list of weakref's is very
suitable for this, as it won't keep the instance objects
alive when there is no need for them to be any more.


> 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?

What's going on is that your references to instances of class K are
not being placed in global variables of the module where K is defined,
just like in my obj1=[K()] example above.


Alex






More information about the Python-list mailing list