Newbie (read: pot. stupid) question on objects/namespaces

Fred Pacquier fredp at
Tue Aug 31 10:57:21 EDT 1999

stephan at (Stephan Houben) said :

>Let me try to rephrase the question first:
>You want to know if it is possible to find out, given a class or
>instance variable, to get at the class or instance.

Yes, that is a much shorter and more correct formulation !

>Short answer: "no".

Hmm. Somehow I felt that one coming :-)

>Longer answer: 
>This is really a tricky problem what "class or instance variable"
>actually means in Python. If you have a class like this:
>class Foo:
>    x = 1
>, then Foo.x refers to the number 1, which is an object in Python.
>Many other classes Bar, Baz, and instances of those, might have
>references to the same object 1. So 1 doesn't really have a single


>Now, you could have a dedicated object which registers its official
>"owner". Say you do that in this way:
>class MyClass:
>    def __init__(self, owner):
>        self.owner = owner
>You create instances of this object like this:
>class Bar:
>    x = MyClass(Bar)
>, or, if you want to have the instance, rather than the class, as owner:
>class Baz:
>    def __init__(self):
>        self.x = MyClass(self)

Yes, that is indeed very close to the result I was looking for. I might 
even have stumbled upon something similar eventually, without ever 
realizing that:

>Note that in *both* cases you create a circular reference which means
>that CPython cannot reclaim the class Bar or the instance of Baz.

Duh. Is this a total "no-no", or what ? If this is only for a handful of 
instances that are supposed to persist through the entire program lifetime, 
is it okay to explicitely del() them at the end or not ?

Thank you very much anyway for a very clear explanation !


More information about the Python-list mailing list