codekingpro/portable-devtools
114k
1# Copyright 2018 Google LLC2#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 at6#7# https://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14 15import functools16 17 18def has_upb():19 try:20 from google._upb import _message # pylint: disable=unused-import21 22 has_upb = True23 except ImportError:24 has_upb = False25 return has_upb26 27 28def cached_property(fx):29 """Make the callable into a cached property.30 31 Similar to @property, but the function will only be called once per32 object.33 34 Args:35 fx (Callable[]): The property function.36 37 Returns:38 Callable[]: The wrapped function.39 """40 41 @functools.wraps(fx)42 def inner(self):43 # Sanity check: If there is no cache at all, create an empty cache.44 if not hasattr(self, "_cached_values"):45 object.__setattr__(self, "_cached_values", {})46 47 # If and only if the function's result is not in the cache,48 # run the function.49 if fx.__name__ not in self._cached_values:50 self._cached_values[fx.__name__] = fx(self)51 52 # Return the value from cache.53 return self._cached_values[fx.__name__]54 55 return property(inner)56 57 58__all__ = ("cached_property",)59 