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

Stephan Houben stephan at pcrm.win.tue.nl
Tue Aug 31 09:42:54 EDT 1999


fredp at multimania.com.nospam (Fred Pacquier) writes:

> Hi,
> 
> I tried looking this up in the FAQ/tutorial and failed, but maybe it's a 
> terminology problem.
> 
> I'd like to know if it is possible, given the name of a "data attribute", 
> to find out the name of its "owner", ie the instance (namespace) where it 
> has been _created_ (the instance, not the class). This is probably unclear, 
> so to illustrate :
> 
> def func(a_thing,...)
>     	...
> 
> class foo:
>     	self.thing = ...
> 
> class bar:
>     	self.a_foo = foo()
>     	func(self.a_foo.thing,...)
> 
> Here, 'func' (might be anywhere, top-level, another class, in the same 
> module if it helps...) receives the data attribute 'thing' of instance 'a-
> foo' of class 'foo'. This instance was created (by ? inside ?) class bar, 
> or (probably) an instance 'a_bar' of class 'bar'.
> 
> The question is: given the simple call above with only the name as a 
> parameter, is there a (legal) way for function 'func' to determine that 
> 'a_thing' actually (lives in ? belongs to ?) 'bar' (or 'a_bar') ?

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.

Short answer: "no".

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 "owner".

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)

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

Greetings,

Stephan 




More information about the Python-list mailing list