[Python-Dev] Oberver Pattern

Guido van Rossum guido@python.org
Fri, 10 May 2002 20:21:33 -0400


> How about a simpler alternative?
> 
> Have just a single field in PyObject_HEAD, int cache_valid.  

This would add 4 bytes to all objects, not just to mutable
containers.  E.g. ints would grow from 12 to 16 bytes!!!

Also, it would break binary compatibility (which we try to maintain
for 3rd party extensions, despite appearances).

> Update routines wouldn't even need a jump.  
> Everywhere the object assigns a value to ob_item[i], it would also run:  
> PyObject_INVALIDATE_CACHE which would expand to:  
>    self->cache_valid=0.

If this field could somehow exist only for mutable containers it
*might* work.  The type object could contain the offset of the field
in the instances (like we use for weakrefs and for the dict offset).

It's not a full observer pattern because it doesn't call anything, so
algorithms that require notification aren't going to work (you'd have
to check the cache flag in each object to see if you need to redisplay
it, for example).

> > If you *have* to do this, I would implement (at the C level) just a
> > single observer object.  If multiple observers are needed, this can
> > easily be done using an adapter in Python.
> 
> Will do.  Since it's not that hard to implement (meaning, less time
> than I spent on iterzip), I may as well try it and time it.

But the impact is much bigger, because it potentially affects many
files.  I'm skeptical.  OTOH, Jim Fulton gave this a +100 on an
internal list.  But he also wants notification upon access. :-)

--Guido van Rossum (home page: http://www.python.org/~guido/)