_factories.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from datetime import timedelta
  2. import weakref
  3. from collections import OrderedDict
  4. from six.moves import _thread
  5. class _TzSingleton(type):
  6. def __init__(cls, *args, **kwargs):
  7. cls.__instance = None
  8. super(_TzSingleton, cls).__init__(*args, **kwargs)
  9. def __call__(cls):
  10. if cls.__instance is None:
  11. cls.__instance = super(_TzSingleton, cls).__call__()
  12. return cls.__instance
  13. class _TzFactory(type):
  14. def instance(cls, *args, **kwargs):
  15. """Alternate constructor that returns a fresh instance"""
  16. return type.__call__(cls, *args, **kwargs)
  17. class _TzOffsetFactory(_TzFactory):
  18. def __init__(cls, *args, **kwargs):
  19. cls.__instances = weakref.WeakValueDictionary()
  20. cls.__strong_cache = OrderedDict()
  21. cls.__strong_cache_size = 8
  22. cls._cache_lock = _thread.allocate_lock()
  23. def __call__(cls, name, offset):
  24. if isinstance(offset, timedelta):
  25. key = (name, offset.total_seconds())
  26. else:
  27. key = (name, offset)
  28. instance = cls.__instances.get(key, None)
  29. if instance is None:
  30. instance = cls.__instances.setdefault(key,
  31. cls.instance(name, offset))
  32. # This lock may not be necessary in Python 3. See GH issue #901
  33. with cls._cache_lock:
  34. cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
  35. # Remove an item if the strong cache is overpopulated
  36. if len(cls.__strong_cache) > cls.__strong_cache_size:
  37. cls.__strong_cache.popitem(last=False)
  38. return instance
  39. class _TzStrFactory(_TzFactory):
  40. def __init__(cls, *args, **kwargs):
  41. cls.__instances = weakref.WeakValueDictionary()
  42. cls.__strong_cache = OrderedDict()
  43. cls.__strong_cache_size = 8
  44. cls.__cache_lock = _thread.allocate_lock()
  45. def __call__(cls, s, posix_offset=False):
  46. key = (s, posix_offset)
  47. instance = cls.__instances.get(key, None)
  48. if instance is None:
  49. instance = cls.__instances.setdefault(key,
  50. cls.instance(s, posix_offset))
  51. # This lock may not be necessary in Python 3. See GH issue #901
  52. with cls.__cache_lock:
  53. cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
  54. # Remove an item if the strong cache is overpopulated
  55. if len(cls.__strong_cache) > cls.__strong_cache_size:
  56. cls.__strong_cache.popitem(last=False)
  57. return instance