Identical descriptor value, without leaking memory?

Jack Bates ms419 at freezone.co.uk
Mon Jul 25 19:46:10 CEST 2011


How can you get a descriptor to return an identical value, each time
it's called with the same "instance" - without leaking memory?


#!/usr/bin/env python

class descriptor:
  class __metaclass__(type):
    def __get__(self, instance, owner):
      ...

class owner:
  descriptor = descriptor

instance = owner()


I want ">>> instance.descriptor is instance.descriptor" to evaluate True

I was thinking of "caching" descriptor return values? Like a dictionary
of instances and descriptor return values? I was thinking of using
weakref.WeakKeyDictionary to avoid leaking memory? But I can't guarantee
that the descriptor return value won't indirectly reference the
instance, in which case weakref.WeakKeyDictionary *does* leak memory?

Does anyone know how to get a descriptor to return an identical value,
each time it's called with the same "instance" - without leaking memory?

Much thanks!



More information about the Python-list mailing list