Simple Acquisition, without proxies nor circular references

Just van Rossum just at
Wed Mar 29 15:54:59 CEST 2000

Not sure if this is a) a new approach and b) whether it is at all useful,
but it occurred to me the there is a simple way to do attribute 
acquisition, without the overhead of proxies, while still not creating
circular references. The trick is to use a custom attribute dict, and
reference that dict from containing objects instead of the objects
itself. I've pasted a small example below. The naming convention
used is: any attribute name starting with an underscore will *not*
be acquired by children, all others are.

Comments anyone?


class Node:
	__instancecount__ = 0  # for testing only
	def __init__(self, container=None):
		if container is None:
			self.__names__ = ({},)
			self.__names__ = ({},) + container.__names__
		self._children = []
		Node.__instancecount__ = Node.__instancecount__ + 1
	def add(self, node):
	def __setattr__(self, attr, value):
		if attr[0] == "_":
			self.__dict__[attr] = value
			self.__names__[0][attr] = value
	def __getattr__(self, attr):
		for dict in self.__names__:
			if dict.has_key(attr):
				return dict[attr]
		raise AttributeError, attr
	def __del__(self):
		Node.__instancecount__ = Node.__instancecount__ - 1

root = Node()

n1 = Node(root)
n2 = Node(root)

n3 = Node(n2)

root.color = "Red"
print "should be Red:", n1.color
print "should be Red:", n2.color
print "should be Red:", n3.color
root.color = "Blue"
n2.color = "Yellow"
print "should be Blue:", n1.color
print "should be Yellow:", n2.color
print "should be Yellow:", n3.color

del root, n1, n2, n3

if Node.__instancecount__:
	print "There are %s Nodes still alive" % Node.__instancecount__
	print "No Nodes left."

More information about the Python-list mailing list