Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/dateutil/tz/_factories.py: 57%

49 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-08 06:05 +0000

1from datetime import timedelta 

2import weakref 

3from collections import OrderedDict 

4 

5from six.moves import _thread 

6 

7 

8class _TzSingleton(type): 

9 def __init__(cls, *args, **kwargs): 

10 cls.__instance = None 

11 super(_TzSingleton, cls).__init__(*args, **kwargs) 

12 

13 def __call__(cls): 

14 if cls.__instance is None: 

15 cls.__instance = super(_TzSingleton, cls).__call__() 

16 return cls.__instance 

17 

18 

19class _TzFactory(type): 

20 def instance(cls, *args, **kwargs): 

21 """Alternate constructor that returns a fresh instance""" 

22 return type.__call__(cls, *args, **kwargs) 

23 

24 

25class _TzOffsetFactory(_TzFactory): 

26 def __init__(cls, *args, **kwargs): 

27 cls.__instances = weakref.WeakValueDictionary() 

28 cls.__strong_cache = OrderedDict() 

29 cls.__strong_cache_size = 8 

30 

31 cls._cache_lock = _thread.allocate_lock() 

32 

33 def __call__(cls, name, offset): 

34 if isinstance(offset, timedelta): 

35 key = (name, offset.total_seconds()) 

36 else: 

37 key = (name, offset) 

38 

39 instance = cls.__instances.get(key, None) 

40 if instance is None: 

41 instance = cls.__instances.setdefault(key, 

42 cls.instance(name, offset)) 

43 

44 # This lock may not be necessary in Python 3. See GH issue #901 

45 with cls._cache_lock: 

46 cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) 

47 

48 # Remove an item if the strong cache is overpopulated 

49 if len(cls.__strong_cache) > cls.__strong_cache_size: 

50 cls.__strong_cache.popitem(last=False) 

51 

52 return instance 

53 

54 

55class _TzStrFactory(_TzFactory): 

56 def __init__(cls, *args, **kwargs): 

57 cls.__instances = weakref.WeakValueDictionary() 

58 cls.__strong_cache = OrderedDict() 

59 cls.__strong_cache_size = 8 

60 

61 cls.__cache_lock = _thread.allocate_lock() 

62 

63 def __call__(cls, s, posix_offset=False): 

64 key = (s, posix_offset) 

65 instance = cls.__instances.get(key, None) 

66 

67 if instance is None: 

68 instance = cls.__instances.setdefault(key, 

69 cls.instance(s, posix_offset)) 

70 

71 # This lock may not be necessary in Python 3. See GH issue #901 

72 with cls.__cache_lock: 

73 cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) 

74 

75 # Remove an item if the strong cache is overpopulated 

76 if len(cls.__strong_cache) > cls.__strong_cache_size: 

77 cls.__strong_cache.popitem(last=False) 

78 

79 return instance 

80