Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- from collections import deque
- from itertools import islice
- from operator import itemgetter
- class Property:
- """
- Getter/Setter class which must be set multiple times
- with an equal object to fit the maxlen.
- A timeout make it possible to remove too old objects.
- The condition is only fulfilled if:
- - all objects are equal
- - the time delta between the objects must be lesser than `timeout`
- If the condition is not fulfilled, the dtype() will return instead.
- """
- def __init__(self, maxlen=2, timeout=2, dtype=str):
- self._instances = {}
- self._maxlen = maxlen
- self.timeout = timeout
- self.dtype = dtype
- def _get_diffs(self, instance):
- return [t2 - t1 for (_, t1), (_, t2) in self._zip_pairwise(instance)]
- def _zip_pairwise(self, instance):
- data = self._instances[instance]
- return zip(islice(data, 0, None), islice(data, 1, None))
- def _remove_old(self, instance):
- diffs = self._get_diffs(instance)
- for idx, diff in enumerate(diffs):
- if diff > self.timeout:
- del self._instances[instance][idx]
- def _all_eq(self, instance):
- return all(a == b for (a, _), (b, _) in self._zip_pairwise(instance))
- def __get__(self, obj, objtype=None):
- if obj in self._instances:
- data = self._instances[obj]
- if len(data) == self._maxlen and self._all_eq(obj):
- return data[-1][0]
- return self.dtype()
- def __set__(self, obj, value):
- if obj not in self._instances:
- self._instances[obj] = deque(maxlen=self._maxlen)
- self._instances[obj].append((value, time.monotonic()))
- self._remove_old(obj)
- class Test:
- error = Property(maxlen=3, timeout=2, dtype=str)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement