local.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. # -*- coding: utf-8 -*-
  2. """Proxy/PromiseProxy implementation.
  3. This module contains critical utilities that needs to be loaded as
  4. soon as possible, and that shall not load any third party modules.
  5. Parts of this module is Copyright by Werkzeug Team.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  8. import importlib
  9. import sys
  10. from .five import bytes_if_py2, string
  11. __all__ = ['Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate']
  12. __module__ = __name__ # used by Proxy class body
  13. PY3 = sys.version_info[0] == 3
  14. def _default_cls_attr(name, type_, cls_value):
  15. # Proxy uses properties to forward the standard
  16. # class attributes __module__, __name__ and __doc__ to the real
  17. # object, but these needs to be a string when accessed from
  18. # the Proxy class directly. This is a hack to make that work.
  19. # -- See Issue #1087.
  20. def __new__(cls, getter):
  21. instance = type_.__new__(cls, cls_value)
  22. instance.__getter = getter
  23. return instance
  24. def __get__(self, obj, cls=None):
  25. return self.__getter(obj) if obj is not None else self
  26. return type(bytes_if_py2(name), (type_,), {
  27. '__new__': __new__, '__get__': __get__,
  28. })
  29. def try_import(module, default=None):
  30. """Try to import and return module, or return
  31. None if the module does not exist."""
  32. try:
  33. return importlib.import_module(module)
  34. except ImportError:
  35. return default
  36. class Proxy(object):
  37. """Proxy to another object."""
  38. # Code stolen from werkzeug.local.Proxy.
  39. __slots__ = ('__local', '__args', '__kwargs', '__dict__')
  40. def __init__(self, local,
  41. args=None, kwargs=None, name=None, __doc__=None):
  42. object.__setattr__(self, '_Proxy__local', local)
  43. object.__setattr__(self, '_Proxy__args', args or ())
  44. object.__setattr__(self, '_Proxy__kwargs', kwargs or {})
  45. if name is not None:
  46. object.__setattr__(self, '__custom_name__', name)
  47. if __doc__ is not None:
  48. object.__setattr__(self, '__doc__', __doc__)
  49. @_default_cls_attr('name', str, __name__)
  50. def __name__(self):
  51. try:
  52. return self.__custom_name__
  53. except AttributeError:
  54. return self._get_current_object().__name__
  55. @_default_cls_attr('qualname', str, __name__)
  56. def __qualname__(self):
  57. try:
  58. return self.__custom_name__
  59. except AttributeError:
  60. return self._get_current_object().__qualname__
  61. @_default_cls_attr('module', str, __module__)
  62. def __module__(self):
  63. return self._get_current_object().__module__
  64. @_default_cls_attr('doc', str, __doc__)
  65. def __doc__(self):
  66. return self._get_current_object().__doc__
  67. def _get_class(self):
  68. return self._get_current_object().__class__
  69. @property
  70. def __class__(self):
  71. return self._get_class()
  72. def _get_current_object(self):
  73. """Return the current object. This is useful if you want the real
  74. object behind the proxy at a time for performance reasons or because
  75. you want to pass the object into a different context."""
  76. loc = object.__getattribute__(self, '_Proxy__local')
  77. if not hasattr(loc, '__release_local__'):
  78. return loc(*self.__args, **self.__kwargs)
  79. try: # pragma: no cover
  80. # not sure what this is about
  81. return getattr(loc, self.__name__)
  82. except AttributeError: # pragma: no cover
  83. raise RuntimeError('no object bound to {0.__name__}'.format(self))
  84. @property
  85. def __dict__(self):
  86. try:
  87. return self._get_current_object().__dict__
  88. except RuntimeError: # pragma: no cover
  89. raise AttributeError('__dict__')
  90. def __repr__(self):
  91. try:
  92. obj = self._get_current_object()
  93. except RuntimeError: # pragma: no cover
  94. return '<{0} unbound>'.format(self.__class__.__name__)
  95. return repr(obj)
  96. def __bool__(self):
  97. try:
  98. return bool(self._get_current_object())
  99. except RuntimeError: # pragma: no cover
  100. return False
  101. __nonzero__ = __bool__ # Py2
  102. def __dir__(self):
  103. try:
  104. return dir(self._get_current_object())
  105. except RuntimeError: # pragma: no cover
  106. return []
  107. def __getattr__(self, name):
  108. if name == '__members__':
  109. return dir(self._get_current_object())
  110. return getattr(self._get_current_object(), name)
  111. def __setitem__(self, key, value):
  112. self._get_current_object()[key] = value
  113. def __delitem__(self, key):
  114. del self._get_current_object()[key]
  115. def __setslice__(self, i, j, seq):
  116. self._get_current_object()[i:j] = seq
  117. def __delslice__(self, i, j):
  118. del self._get_current_object()[i:j]
  119. def __setattr__(self, name, value):
  120. setattr(self._get_current_object(), name, value)
  121. def __delattr__(self, name):
  122. delattr(self._get_current_object(), name)
  123. def __str__(self):
  124. return str(self._get_current_object())
  125. def __lt__(self, other):
  126. return self._get_current_object() < other
  127. def __le__(self, other):
  128. return self._get_current_object() <= other
  129. def __eq__(self, other):
  130. return self._get_current_object() == other
  131. def __ne__(self, other):
  132. return self._get_current_object() != other
  133. def __gt__(self, other):
  134. return self._get_current_object() > other
  135. def __ge__(self, other):
  136. return self._get_current_object() >= other
  137. def __hash__(self):
  138. return hash(self._get_current_object())
  139. def __call__(self, *a, **kw):
  140. return self._get_current_object()(*a, **kw)
  141. def __len__(self):
  142. return len(self._get_current_object())
  143. def __getitem__(self, i):
  144. return self._get_current_object()[i]
  145. def __iter__(self):
  146. return iter(self._get_current_object())
  147. def __contains__(self, i):
  148. return i in self._get_current_object()
  149. def __getslice__(self, i, j):
  150. return self._get_current_object()[i:j]
  151. def __add__(self, other):
  152. return self._get_current_object() + other
  153. def __sub__(self, other):
  154. return self._get_current_object() - other
  155. def __mul__(self, other):
  156. return self._get_current_object() * other
  157. def __floordiv__(self, other):
  158. return self._get_current_object() // other
  159. def __mod__(self, other):
  160. return self._get_current_object() % other
  161. def __divmod__(self, other):
  162. return self._get_current_object().__divmod__(other)
  163. def __pow__(self, other):
  164. return self._get_current_object() ** other
  165. def __lshift__(self, other):
  166. return self._get_current_object() << other
  167. def __rshift__(self, other):
  168. return self._get_current_object() >> other
  169. def __and__(self, other):
  170. return self._get_current_object() & other
  171. def __xor__(self, other):
  172. return self._get_current_object() ^ other
  173. def __or__(self, other):
  174. return self._get_current_object() | other
  175. def __div__(self, other):
  176. return self._get_current_object().__div__(other)
  177. def __truediv__(self, other):
  178. return self._get_current_object().__truediv__(other)
  179. def __neg__(self):
  180. return -(self._get_current_object())
  181. def __pos__(self):
  182. return +(self._get_current_object())
  183. def __abs__(self):
  184. return abs(self._get_current_object())
  185. def __invert__(self):
  186. return ~(self._get_current_object())
  187. def __complex__(self):
  188. return complex(self._get_current_object())
  189. def __int__(self):
  190. return int(self._get_current_object())
  191. def __float__(self):
  192. return float(self._get_current_object())
  193. def __oct__(self):
  194. return oct(self._get_current_object())
  195. def __hex__(self):
  196. return hex(self._get_current_object())
  197. def __index__(self):
  198. return self._get_current_object().__index__()
  199. def __coerce__(self, other):
  200. return self._get_current_object().__coerce__(other)
  201. def __enter__(self):
  202. return self._get_current_object().__enter__()
  203. def __exit__(self, *a, **kw):
  204. return self._get_current_object().__exit__(*a, **kw)
  205. def __reduce__(self):
  206. return self._get_current_object().__reduce__()
  207. if not PY3: # pragma: no cover
  208. def __cmp__(self, other):
  209. return cmp(self._get_current_object(), other) # noqa
  210. def __long__(self):
  211. return long(self._get_current_object()) # noqa
  212. def __unicode__(self):
  213. try:
  214. return string(self._get_current_object())
  215. except RuntimeError: # pragma: no cover
  216. return repr(self)
  217. class PromiseProxy(Proxy):
  218. """This is a proxy to an object that hasn't yet been evaulated.
  219. :class:`Proxy` will evaluate the object each time, while the
  220. promise will only evaluate it once.
  221. """
  222. __slots__ = ('__pending__',)
  223. def _get_current_object(self):
  224. try:
  225. return object.__getattribute__(self, '__thing')
  226. except AttributeError:
  227. return self.__evaluate__()
  228. def __then__(self, fun, *args, **kwargs):
  229. if self.__evaluated__():
  230. return fun(*args, **kwargs)
  231. from collections import deque
  232. try:
  233. pending = object.__getattribute__(self, '__pending__')
  234. except AttributeError:
  235. pending = None
  236. if pending is None:
  237. pending = deque()
  238. object.__setattr__(self, '__pending__', pending)
  239. pending.append((fun, args, kwargs))
  240. def __evaluated__(self):
  241. try:
  242. object.__getattribute__(self, '__thing')
  243. except AttributeError:
  244. return False
  245. return True
  246. def __maybe_evaluate__(self):
  247. return self._get_current_object()
  248. def __evaluate__(self,
  249. _clean=('_Proxy__local',
  250. '_Proxy__args',
  251. '_Proxy__kwargs')):
  252. try:
  253. thing = Proxy._get_current_object(self)
  254. except:
  255. raise
  256. else:
  257. object.__setattr__(self, '__thing', thing)
  258. for attr in _clean:
  259. try:
  260. object.__delattr__(self, attr)
  261. except AttributeError: # pragma: no cover
  262. # May mask errors so ignore
  263. pass
  264. try:
  265. pending = object.__getattribute__(self, '__pending__')
  266. except AttributeError:
  267. pass
  268. else:
  269. try:
  270. while pending:
  271. fun, args, kwargs = pending.popleft()
  272. fun(*args, **kwargs)
  273. finally:
  274. try:
  275. object.__delattr__(self, '__pending__')
  276. except AttributeError: # pragma: no cover
  277. pass
  278. return thing
  279. def maybe_evaluate(obj):
  280. try:
  281. return obj.__maybe_evaluate__()
  282. except AttributeError:
  283. return obj