Aquiles Carattino
Aquiles Carattino

Reputation: 930

Object property with extra functions in Python

I am developing a descriptor basing myself in the ideas of @property. What I would like is to understand if there is any way of easily extending the behavior of property beyond setting/getting.

The concrete example: I am communicating with a device, and would like to have a property that can set/get/update. In this way, when I set, I pass the new value to the device, and store it in the cache. When I get, I retrieve the cached value. When I update, the device is re-asked for the value. In this way, can avoid unnecessary communication with the device, unless explicitly triggered.

I don't know if there is a pattern that I am missing that may be a straightforward solution. An option would be to invalidate the cache when using a special value in set, but I don't think it is a good idea to assume a specific value for triggering the update.

Upvotes: 1

Views: 138

Answers (1)

mapf
mapf

Reputation: 2058

I still don't understand the difference between your getter and updater, but here is some sample code which implements a cache that stores previous variable values. Maybe this helps you to find what you are looking for.

class A:
    def __init__(self):
        self._a_cache = [1]

    @property  # <- this defines a.getter
    def a(self):
        return self._a_cache[-1]

    @a.setter
    def a(self, value):
        self._a_cache.append(value)

    def undo(self):
        if len(self._a_cache) > 1:
            self._a_cache.pop()
        else:
            print('No previous values')

    def update(self):
        # what is supposed to happen here as opposed to the getter?
        pass
        
        
var = A()
print(var.a)

var.a = 10
print(var.a)

var.undo()
print(var.a)

var.update()
# ?

Upvotes: 1

Related Questions