Object instance "reporting" to a container class instance

D

Daniel Lipovetsky

I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.

class AnyObject:
pass

class Container:
links = []
def add(self,other):
while other not in self.links:
self.links.append(other)
def rem(self,other):
while other in self.links:
self.links.remove(other)
....

container = Container()
a = AnyObject()
container.add(a)

My question is: can (should? :) this "reporting" be done inside the
instance's __init__ and __del__ methods (that is, an instance
"reports" to the container as soon as it is created or deleted)?

Thanks!
Daniel

---

I'm working out a design where Object A is "linked" to Object B, and
both objects become aware of that relationship. I have implemented an
example successfully; the code is below. My main question is above,
but I would appreciate comments on the code! (For example, I'm
wondering whether my way of defining variables in the class but
assigning them locally to each instance (in the "Object.init" method)
is really a bad kludge...)


class Object():
def __del__(self):
print "buh-bye!", self # Verbose for understanding garbage cleanup
def init(self,name):
self.links = []
self.name = name
def add(self,other):
while other not in self.links:
self.links.append(other)
other.add(self)
def rem(self,other):
while other in self.links:
self.links.remove(other)
other.rem(self)

class Student(Object):
def __init__(self,name):
self.init(name)

class Section(Object):
def __init__(self,name):
self.init(name)

class Task(Object):
def __init__(self,name):
self.init(name)

## Construct test instances!

students = {}
for name in ['Jose','Daniel','Rusty']:
student = Student(name)
students[name] = student

sections = {}
for name in ['English 1']:
section = Section(name)
sections[name] = section

tasks = {}
for name in ['Homework 1','Exam 1','Homework 2','Exam 2']:
task = Task(name)
tasks[name] = task

# Display example connections
def show_connections():
for section in sections:
print sections[section].name
for link in sections[section].links:
print "\t", link.name

# Add some connections...

print "Now adding connections..."
for name in tasks:
sections['English 1'].add(tasks[name])
show_connections()

# Remove some connections...

print "Now removing connections..."
for name in tasks:
sections['English 1'].rem(tasks[name])
show_connections()

for task in tasks:
print tasks[task].links

for section in sections:
print sections[section].links

## Test garbage cleanup

sections['English 1'].add(tasks['Exam 1'])
print sections['English 1'].links
sections['English 1'].rem(tasks['Exam 1'])
del sections['English 1']
 
A

Alex Martelli

Daniel Lipovetsky said:
I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.

class AnyObject:
pass

class Container:
links = []

Why a class variable rather than a normal instance variable?
def add(self,other):
while other not in self.links:
self.links.append(other)

What a weird implementation... why the while, &c?!
def rem(self,other):
while other in self.links:
self.links.remove(other)
Ditto.

...

container = Container()
a = AnyObject()
container.add(a)

My question is: can (should? :) this "reporting" be done inside the
instance's __init__ and __del__ methods (that is, an instance
"reports" to the container as soon as it is created or deleted)?

The object's __del__ will never be called, because the object's presence
in the Container's self.links will always keep the object alive.

Study weak references -- and make the Container's links (whether it
needs to be a class or instance variable for the container) a
weakref.WeakValueDictionary (as keys, use unique, always-incrementing
integers) -- a WeakKeyDictionary is OK too if contained objects are
hashable by identity (and might make other things easier, e.g. moving an
object from one container to another by removing it from one and adding
it from the other).

With weak references, the "reporting" of the object's demise will be
automatic and transparent - the relevant dict entry just disappears when
the object does. For the "registration", the call to the add method of
the container, it's fine to do it in __init__ if at contained-object's
init time you already know, invariably, what container it will be in.


Alex
 
J

Jordan Greenberg

Daniel said:
I would like for an object to "report" to a container object when a
new instance is created or deleted. I could have a container object
that is called when a new instance is created, as below.

I've run into a similar problem before, in my case it was easiest to
allow the container to create the new instances, sort of like:

<CODE>

class Something(object):
def __init__(self, *args):
self.x=args

class Container(object):
def __init__(self):
self.instances=[]

def newinstance(self, newclass, *args):
tmp=newclass(args)
self.instances.append(tmp)
return tmp

def delinstance(self, inst):
self.instances.remove(inst)
cont=Container()
a=cont.newinstance(Something, 5, 6)
b=cont.newinstance(Something, 7, 8)
c=cont.newinstance(Something, 8, 9)

print len(cont.instances)

cont.delinstance(b)
print len(cont.instances)

#note that b is still defined, unless you remove that name explicitly...
print b
del b
print b

</CODE>

This can be very, very, very ugly. I don't particularly actually
recommend doing anything like this. Usually you should re-think your
organization to make this unnecessary. I suppose, though, it can come in
handy in certain situations.

-Jordan G
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top