Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10554

Re: Identical descriptor value, without leaking memory?

References <1311615971.22847.26.camel@selene>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-07-29 17:01 -0600
Subject Re: Identical descriptor value, without leaking memory?
Newsgroups comp.lang.python
Message-ID <mailman.1642.1311980495.1164.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jul 25, 2011 at 11:46 AM, Jack Bates <ms419@freezone.co.uk> wrote:
> How can you get a descriptor to return an identical value, each time
> it's called with the same "instance" - without leaking memory?

class MyDescriptor(object):
    def __get__(self, instance, owner):
        try:
            return instance.__cached_value[self]
        except AttributeError:
            instance.__cached_value = {self: get_value(instance, owner)}
        except KeyError:
            instance.__cached_value[self] = get_value(instance, owner)
        return instance.__cached_value

class MyClass(object):
    my_attribute = MyDescriptor()


Placing the cache on the object instance ensures that it won't outlive
the object, and since the full attribute name will be
_MyDescriptor__cached_value, it's highly unlikely to conflict with an
existing attribute.  Keying the value on self is necessary in case the
object has multiple descriptors of the same type.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Identical descriptor value, without leaking memory? Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-29 17:01 -0600

csiph-web