How evil is this use of sys.getrefcount?

Miles semanticist at
Sat Mar 21 00:45:50 CET 2009

On Fri, Mar 20, 2009 at 6:27 PM, Brian Cole wrote:
> I'm trying to cache the construction and destruction of an expensive
> object coming out of a generator function. I can do the following to
> force a new object to be used if the object is being used somewhere
> else (based upon it's reference count). Here is the pseudo-code of
> what I am trying to accomplish.
> def GetExpensiveObjects():
>    obj = ExpensiveObject()
>    baserefs = sys.getrefcount(obj)
>    while UpdateExpensiveObject(obj):
>        yield obj
>        if sys.getrefcount(obj) > baseline + 1:
>            obj = ExpensiveObject()

Seems pretty evil to me!  My approach would probably either be to have
two generators and allow the user to decide if they want the object to
be valid after a subsequent call to the iterator, or to use a wrapper
object like the following:

class ExpensiveProxy(object):
    _cache = []

    def __init__(self):
        if self.cache:
            self._object = self._cache.pop()
            self._object = ExpensiveObject()

    def __del__(self):

    # Define your own methods to wrap those of the object,
    # or maybe define __getattr__


More information about the Python-list mailing list