|
| 1 | +# Copyright 2018 The dm_control Authors. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================ |
| 15 | + |
| 16 | +"""Decorators for Entity methods returning elements and observables.""" |
| 17 | + |
| 18 | +from __future__ import absolute_import |
| 19 | +from __future__ import division |
| 20 | +from __future__ import print_function |
| 21 | + |
| 22 | +import abc |
| 23 | +import threading |
| 24 | + |
| 25 | + |
| 26 | +class cached_property(property): # pylint: disable=invalid-name |
| 27 | + """A property that is evaluated only once per object instance.""" |
| 28 | + |
| 29 | + def __init__(self, func, doc=None): |
| 30 | + super(cached_property, self).__init__(fget=func, doc=doc) |
| 31 | + self.lock = threading.RLock() |
| 32 | + |
| 33 | + def __get__(self, obj, cls): |
| 34 | + if obj is None: |
| 35 | + return self |
| 36 | + name = self.fget.__name__ |
| 37 | + obj_dict = obj.__dict__ |
| 38 | + try: |
| 39 | + # Try returning a precomputed value without locking first. |
| 40 | + # Profiling shows that the lock takes up a non-trivial amount of time. |
| 41 | + return obj_dict[name] |
| 42 | + except KeyError: |
| 43 | + # The value hasn't been computed, now we have to lock. |
| 44 | + with self.lock: |
| 45 | + try: |
| 46 | + # Check again whether another thread has already computed the value. |
| 47 | + return obj_dict[name] |
| 48 | + except KeyError: |
| 49 | + # Otherwise call the function, cache the result, and return it |
| 50 | + return obj_dict.setdefault(name, self.fget(obj)) |
| 51 | + |
| 52 | + |
| 53 | +# A decorator for base.Observables methods returning an observable. This |
| 54 | +# decorator should be used by abstract base classes to indicate sub-classes need |
| 55 | +# to implement a corresponding @observavble annotated method. |
| 56 | +abstract_observable = abc.abstractproperty # pylint: disable=invalid-name |
| 57 | + |
| 58 | + |
| 59 | +class observable(cached_property): # pylint: disable=invalid-name |
| 60 | + """A decorator for base.Observables methods returning an observable. |
| 61 | +
|
| 62 | + The body of the decorated function is evaluated at Entity construction time |
| 63 | + and the observable is cached. |
| 64 | + """ |
| 65 | + pass |
0 commit comments