Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/proto/utils.py: 58%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

19 statements  

1# Copyright 2018 Google LLC 

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# https://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 

15import functools 

16 

17 

18def has_upb(): 

19 try: 

20 from google._upb import _message # pylint: disable=unused-import 

21 

22 has_upb = True 

23 except ImportError: 

24 has_upb = False 

25 return has_upb 

26 

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 per 

32 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",)