local.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. import copy
  2. import math
  3. import operator
  4. import sys
  5. import typing as t
  6. import warnings
  7. from functools import partial
  8. from functools import update_wrapper
  9. from .wsgi import ClosingIterator
  10. if t.TYPE_CHECKING:
  11. from _typeshed.wsgi import StartResponse
  12. from _typeshed.wsgi import WSGIApplication
  13. from _typeshed.wsgi import WSGIEnvironment
  14. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  15. try:
  16. from greenlet import getcurrent as _get_ident
  17. except ImportError:
  18. from threading import get_ident as _get_ident
  19. def get_ident() -> int:
  20. warnings.warn(
  21. "'get_ident' is deprecated and will be removed in Werkzeug"
  22. " 2.1. Use 'greenlet.getcurrent' or 'threading.get_ident' for"
  23. " previous behavior.",
  24. DeprecationWarning,
  25. stacklevel=2,
  26. )
  27. return _get_ident() # type: ignore
  28. class _CannotUseContextVar(Exception):
  29. pass
  30. try:
  31. from contextvars import ContextVar
  32. if "gevent" in sys.modules or "eventlet" in sys.modules:
  33. # Both use greenlet, so first check it has patched
  34. # ContextVars, Greenlet <0.4.17 does not.
  35. import greenlet
  36. greenlet_patched = getattr(greenlet, "GREENLET_USE_CONTEXT_VARS", False)
  37. if not greenlet_patched:
  38. # If Gevent is used, check it has patched ContextVars,
  39. # <20.5 does not.
  40. try:
  41. from gevent.monkey import is_object_patched
  42. except ImportError:
  43. # Gevent isn't used, but Greenlet is and hasn't patched
  44. raise _CannotUseContextVar() from None
  45. else:
  46. if is_object_patched("threading", "local") and not is_object_patched(
  47. "contextvars", "ContextVar"
  48. ):
  49. raise _CannotUseContextVar()
  50. def __release_local__(storage: t.Any) -> None:
  51. # Can remove when support for non-stdlib ContextVars is
  52. # removed, see "Fake" version below.
  53. storage.set({})
  54. except (ImportError, _CannotUseContextVar):
  55. class ContextVar: # type: ignore
  56. """A fake ContextVar based on the previous greenlet/threading
  57. ident function. Used on Python 3.6, eventlet, and old versions
  58. of gevent.
  59. """
  60. def __init__(self, _name: str) -> None:
  61. self.storage: t.Dict[int, t.Dict[str, t.Any]] = {}
  62. def get(self, default: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
  63. return self.storage.get(_get_ident(), default)
  64. def set(self, value: t.Dict[str, t.Any]) -> None:
  65. self.storage[_get_ident()] = value
  66. def __release_local__(storage: t.Any) -> None:
  67. # Special version to ensure that the storage is cleaned up on
  68. # release.
  69. storage.storage.pop(_get_ident(), None)
  70. def release_local(local: t.Union["Local", "LocalStack"]) -> None:
  71. """Releases the contents of the local for the current context.
  72. This makes it possible to use locals without a manager.
  73. Example::
  74. >>> loc = Local()
  75. >>> loc.foo = 42
  76. >>> release_local(loc)
  77. >>> hasattr(loc, 'foo')
  78. False
  79. With this function one can release :class:`Local` objects as well
  80. as :class:`LocalStack` objects. However it is not possible to
  81. release data held by proxies that way, one always has to retain
  82. a reference to the underlying local object in order to be able
  83. to release it.
  84. .. versionadded:: 0.6.1
  85. """
  86. local.__release_local__()
  87. class Local:
  88. __slots__ = ("_storage",)
  89. def __init__(self) -> None:
  90. object.__setattr__(self, "_storage", ContextVar("local_storage"))
  91. @property
  92. def __storage__(self) -> t.Dict[str, t.Any]:
  93. warnings.warn(
  94. "'__storage__' is deprecated and will be removed in Werkzeug 2.1.",
  95. DeprecationWarning,
  96. stacklevel=2,
  97. )
  98. return self._storage.get({}) # type: ignore
  99. @property
  100. def __ident_func__(self) -> t.Callable[[], int]:
  101. warnings.warn(
  102. "'__ident_func__' is deprecated and will be removed in"
  103. " Werkzeug 2.1. It should not be used in Python 3.7+.",
  104. DeprecationWarning,
  105. stacklevel=2,
  106. )
  107. return _get_ident # type: ignore
  108. @__ident_func__.setter
  109. def __ident_func__(self, func: t.Callable[[], int]) -> None:
  110. warnings.warn(
  111. "'__ident_func__' is deprecated and will be removed in"
  112. " Werkzeug 2.1. Setting it no longer has any effect.",
  113. DeprecationWarning,
  114. stacklevel=2,
  115. )
  116. def __iter__(self) -> t.Iterator[t.Tuple[int, t.Any]]:
  117. return iter(self._storage.get({}).items())
  118. def __call__(self, proxy: str) -> "LocalProxy":
  119. """Create a proxy for a name."""
  120. return LocalProxy(self, proxy)
  121. def __release_local__(self) -> None:
  122. __release_local__(self._storage)
  123. def __getattr__(self, name: str) -> t.Any:
  124. values = self._storage.get({})
  125. try:
  126. return values[name]
  127. except KeyError:
  128. raise AttributeError(name) from None
  129. def __setattr__(self, name: str, value: t.Any) -> None:
  130. values = self._storage.get({}).copy()
  131. values[name] = value
  132. self._storage.set(values)
  133. def __delattr__(self, name: str) -> None:
  134. values = self._storage.get({}).copy()
  135. try:
  136. del values[name]
  137. self._storage.set(values)
  138. except KeyError:
  139. raise AttributeError(name) from None
  140. class LocalStack:
  141. """This class works similar to a :class:`Local` but keeps a stack
  142. of objects instead. This is best explained with an example::
  143. >>> ls = LocalStack()
  144. >>> ls.push(42)
  145. >>> ls.top
  146. 42
  147. >>> ls.push(23)
  148. >>> ls.top
  149. 23
  150. >>> ls.pop()
  151. 23
  152. >>> ls.top
  153. 42
  154. They can be force released by using a :class:`LocalManager` or with
  155. the :func:`release_local` function but the correct way is to pop the
  156. item from the stack after using. When the stack is empty it will
  157. no longer be bound to the current context (and as such released).
  158. By calling the stack without arguments it returns a proxy that resolves to
  159. the topmost item on the stack.
  160. .. versionadded:: 0.6.1
  161. """
  162. def __init__(self) -> None:
  163. self._local = Local()
  164. def __release_local__(self) -> None:
  165. self._local.__release_local__()
  166. @property
  167. def __ident_func__(self) -> t.Callable[[], int]:
  168. return self._local.__ident_func__
  169. @__ident_func__.setter
  170. def __ident_func__(self, value: t.Callable[[], int]) -> None:
  171. object.__setattr__(self._local, "__ident_func__", value)
  172. def __call__(self) -> "LocalProxy":
  173. def _lookup() -> t.Any:
  174. rv = self.top
  175. if rv is None:
  176. raise RuntimeError("object unbound")
  177. return rv
  178. return LocalProxy(_lookup)
  179. def push(self, obj: t.Any) -> t.List[t.Any]:
  180. """Pushes a new item to the stack"""
  181. rv = getattr(self._local, "stack", []).copy()
  182. rv.append(obj)
  183. self._local.stack = rv
  184. return rv
  185. def pop(self) -> t.Any:
  186. """Removes the topmost item from the stack, will return the
  187. old value or `None` if the stack was already empty.
  188. """
  189. stack = getattr(self._local, "stack", None)
  190. if stack is None:
  191. return None
  192. elif len(stack) == 1:
  193. release_local(self._local)
  194. return stack[-1]
  195. else:
  196. return stack.pop()
  197. @property
  198. def top(self) -> t.Any:
  199. """The topmost item on the stack. If the stack is empty,
  200. `None` is returned.
  201. """
  202. try:
  203. return self._local.stack[-1]
  204. except (AttributeError, IndexError):
  205. return None
  206. class LocalManager:
  207. """Local objects cannot manage themselves. For that you need a local
  208. manager. You can pass a local manager multiple locals or add them
  209. later by appending them to `manager.locals`. Every time the manager
  210. cleans up, it will clean up all the data left in the locals for this
  211. context.
  212. .. versionchanged:: 2.0
  213. ``ident_func`` is deprecated and will be removed in Werkzeug
  214. 2.1.
  215. .. versionchanged:: 0.6.1
  216. The :func:`release_local` function can be used instead of a
  217. manager.
  218. .. versionchanged:: 0.7
  219. The ``ident_func`` parameter was added.
  220. """
  221. def __init__(
  222. self,
  223. locals: t.Optional[t.Iterable[t.Union[Local, LocalStack]]] = None,
  224. ident_func: None = None,
  225. ) -> None:
  226. if locals is None:
  227. self.locals = []
  228. elif isinstance(locals, Local):
  229. self.locals = [locals]
  230. else:
  231. self.locals = list(locals)
  232. if ident_func is not None:
  233. warnings.warn(
  234. "'ident_func' is deprecated and will be removed in"
  235. " Werkzeug 2.1. Setting it no longer has any effect.",
  236. DeprecationWarning,
  237. stacklevel=2,
  238. )
  239. @property
  240. def ident_func(self) -> t.Callable[[], int]:
  241. warnings.warn(
  242. "'ident_func' is deprecated and will be removed in Werkzeug 2.1.",
  243. DeprecationWarning,
  244. stacklevel=2,
  245. )
  246. return _get_ident # type: ignore
  247. @ident_func.setter
  248. def ident_func(self, func: t.Callable[[], int]) -> None:
  249. warnings.warn(
  250. "'ident_func' is deprecated and will be removedin Werkzeug"
  251. " 2.1. Setting it no longer has any effect.",
  252. DeprecationWarning,
  253. stacklevel=2,
  254. )
  255. def get_ident(self) -> int:
  256. """Return the context identifier the local objects use internally for
  257. this context. You cannot override this method to change the behavior
  258. but use it to link other context local objects (such as SQLAlchemy's
  259. scoped sessions) to the Werkzeug locals.
  260. .. deprecated:: 2.0
  261. Will be removed in Werkzeug 2.1.
  262. .. versionchanged:: 0.7
  263. You can pass a different ident function to the local manager that
  264. will then be propagated to all the locals passed to the
  265. constructor.
  266. """
  267. warnings.warn(
  268. "'get_ident' is deprecated and will be removed in Werkzeug 2.1.",
  269. DeprecationWarning,
  270. stacklevel=2,
  271. )
  272. return self.ident_func()
  273. def cleanup(self) -> None:
  274. """Manually clean up the data in the locals for this context. Call
  275. this at the end of the request or use `make_middleware()`.
  276. """
  277. for local in self.locals:
  278. release_local(local)
  279. def make_middleware(self, app: "WSGIApplication") -> "WSGIApplication":
  280. """Wrap a WSGI application so that cleaning up happens after
  281. request end.
  282. """
  283. def application(
  284. environ: "WSGIEnvironment", start_response: "StartResponse"
  285. ) -> t.Iterable[bytes]:
  286. return ClosingIterator(app(environ, start_response), self.cleanup)
  287. return application
  288. def middleware(self, func: "WSGIApplication") -> "WSGIApplication":
  289. """Like `make_middleware` but for decorating functions.
  290. Example usage::
  291. @manager.middleware
  292. def application(environ, start_response):
  293. ...
  294. The difference to `make_middleware` is that the function passed
  295. will have all the arguments copied from the inner application
  296. (name, docstring, module).
  297. """
  298. return update_wrapper(self.make_middleware(func), func)
  299. def __repr__(self) -> str:
  300. return f"<{type(self).__name__} storages: {len(self.locals)}>"
  301. class _ProxyLookup:
  302. """Descriptor that handles proxied attribute lookup for
  303. :class:`LocalProxy`.
  304. :param f: The built-in function this attribute is accessed through.
  305. Instead of looking up the special method, the function call
  306. is redone on the object.
  307. :param fallback: Return this function if the proxy is unbound
  308. instead of raising a :exc:`RuntimeError`.
  309. :param is_attr: This proxied name is an attribute, not a function.
  310. Call the fallback immediately to get the value.
  311. :param class_value: Value to return when accessed from the
  312. ``LocalProxy`` class directly. Used for ``__doc__`` so building
  313. docs still works.
  314. """
  315. __slots__ = ("bind_f", "fallback", "is_attr", "class_value", "name")
  316. def __init__(
  317. self,
  318. f: t.Optional[t.Callable] = None,
  319. fallback: t.Optional[t.Callable] = None,
  320. class_value: t.Optional[t.Any] = None,
  321. is_attr: bool = False,
  322. ) -> None:
  323. bind_f: t.Optional[t.Callable[["LocalProxy", t.Any], t.Callable]]
  324. if hasattr(f, "__get__"):
  325. # A Python function, can be turned into a bound method.
  326. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  327. return f.__get__(obj, type(obj)) # type: ignore
  328. elif f is not None:
  329. # A C function, use partial to bind the first argument.
  330. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  331. return partial(f, obj) # type: ignore
  332. else:
  333. # Use getattr, which will produce a bound method.
  334. bind_f = None
  335. self.bind_f = bind_f
  336. self.fallback = fallback
  337. self.class_value = class_value
  338. self.is_attr = is_attr
  339. def __set_name__(self, owner: "LocalProxy", name: str) -> None:
  340. self.name = name
  341. def __get__(self, instance: "LocalProxy", owner: t.Optional[type] = None) -> t.Any:
  342. if instance is None:
  343. if self.class_value is not None:
  344. return self.class_value
  345. return self
  346. try:
  347. obj = instance._get_current_object()
  348. except RuntimeError:
  349. if self.fallback is None:
  350. raise
  351. fallback = self.fallback.__get__(instance, owner) # type: ignore
  352. if self.is_attr:
  353. # __class__ and __doc__ are attributes, not methods.
  354. # Call the fallback to get the value.
  355. return fallback()
  356. return fallback
  357. if self.bind_f is not None:
  358. return self.bind_f(instance, obj)
  359. return getattr(obj, self.name)
  360. def __repr__(self) -> str:
  361. return f"proxy {self.name}"
  362. def __call__(self, instance: "LocalProxy", *args: t.Any, **kwargs: t.Any) -> t.Any:
  363. """Support calling unbound methods from the class. For example,
  364. this happens with ``copy.copy``, which does
  365. ``type(x).__copy__(x)``. ``type(x)`` can't be proxied, so it
  366. returns the proxy type and descriptor.
  367. """
  368. return self.__get__(instance, type(instance))(*args, **kwargs)
  369. class _ProxyIOp(_ProxyLookup):
  370. """Look up an augmented assignment method on a proxied object. The
  371. method is wrapped to return the proxy instead of the object.
  372. """
  373. __slots__ = ()
  374. def __init__(
  375. self, f: t.Optional[t.Callable] = None, fallback: t.Optional[t.Callable] = None
  376. ) -> None:
  377. super().__init__(f, fallback)
  378. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  379. def i_op(self: t.Any, other: t.Any) -> "LocalProxy":
  380. f(self, other) # type: ignore
  381. return instance
  382. return i_op.__get__(obj, type(obj)) # type: ignore
  383. self.bind_f = bind_f
  384. def _l_to_r_op(op: F) -> F:
  385. """Swap the argument order to turn an l-op into an r-op."""
  386. def r_op(obj: t.Any, other: t.Any) -> t.Any:
  387. return op(other, obj)
  388. return t.cast(F, r_op)
  389. class LocalProxy:
  390. """A proxy to the object bound to a :class:`Local`. All operations
  391. on the proxy are forwarded to the bound object. If no object is
  392. bound, a :exc:`RuntimeError` is raised.
  393. .. code-block:: python
  394. from werkzeug.local import Local
  395. l = Local()
  396. # a proxy to whatever l.user is set to
  397. user = l("user")
  398. from werkzeug.local import LocalStack
  399. _request_stack = LocalStack()
  400. # a proxy to _request_stack.top
  401. request = _request_stack()
  402. # a proxy to the session attribute of the request proxy
  403. session = LocalProxy(lambda: request.session)
  404. ``__repr__`` and ``__class__`` are forwarded, so ``repr(x)`` and
  405. ``isinstance(x, cls)`` will look like the proxied object. Use
  406. ``issubclass(type(x), LocalProxy)`` to check if an object is a
  407. proxy.
  408. .. code-block:: python
  409. repr(user) # <User admin>
  410. isinstance(user, User) # True
  411. issubclass(type(user), LocalProxy) # True
  412. :param local: The :class:`Local` or callable that provides the
  413. proxied object.
  414. :param name: The attribute name to look up on a :class:`Local`. Not
  415. used if a callable is given.
  416. .. versionchanged:: 2.0
  417. Updated proxied attributes and methods to reflect the current
  418. data model.
  419. .. versionchanged:: 0.6.1
  420. The class can be instantiated with a callable.
  421. """
  422. __slots__ = ("__local", "__name", "__wrapped__", "__dict__")
  423. def __init__(
  424. self,
  425. local: t.Union["Local", t.Callable[[], t.Any]],
  426. name: t.Optional[str] = None,
  427. ) -> None:
  428. object.__setattr__(self, "_LocalProxy__local", local)
  429. object.__setattr__(self, "_LocalProxy__name", name)
  430. if callable(local) and not hasattr(local, "__release_local__"):
  431. # "local" is a callable that is not an instance of Local or
  432. # LocalManager: mark it as a wrapped function.
  433. object.__setattr__(self, "__wrapped__", local)
  434. def _get_current_object(self) -> t.Any:
  435. """Return the current object. This is useful if you want the real
  436. object behind the proxy at a time for performance reasons or because
  437. you want to pass the object into a different context.
  438. """
  439. if not hasattr(self.__local, "__release_local__"): # type: ignore
  440. return self.__local() # type: ignore
  441. try:
  442. return getattr(self.__local, self.__name) # type: ignore
  443. except AttributeError:
  444. name = self.__name # type: ignore
  445. raise RuntimeError(f"no object bound to {name}") from None
  446. __doc__ = _ProxyLookup( # type: ignore
  447. class_value=__doc__, fallback=lambda self: type(self).__doc__, is_attr=True
  448. )
  449. # __del__ should only delete the proxy
  450. __repr__ = _ProxyLookup( # type: ignore
  451. repr, fallback=lambda self: f"<{type(self).__name__} unbound>"
  452. )
  453. __str__ = _ProxyLookup(str) # type: ignore
  454. __bytes__ = _ProxyLookup(bytes)
  455. __format__ = _ProxyLookup() # type: ignore
  456. __lt__ = _ProxyLookup(operator.lt)
  457. __le__ = _ProxyLookup(operator.le)
  458. __eq__ = _ProxyLookup(operator.eq) # type: ignore
  459. __ne__ = _ProxyLookup(operator.ne) # type: ignore
  460. __gt__ = _ProxyLookup(operator.gt)
  461. __ge__ = _ProxyLookup(operator.ge)
  462. __hash__ = _ProxyLookup(hash) # type: ignore
  463. __bool__ = _ProxyLookup(bool, fallback=lambda self: False)
  464. __getattr__ = _ProxyLookup(getattr)
  465. # __getattribute__ triggered through __getattr__
  466. __setattr__ = _ProxyLookup(setattr) # type: ignore
  467. __delattr__ = _ProxyLookup(delattr) # type: ignore
  468. __dir__ = _ProxyLookup(dir, fallback=lambda self: []) # type: ignore
  469. # __get__ (proxying descriptor not supported)
  470. # __set__ (descriptor)
  471. # __delete__ (descriptor)
  472. # __set_name__ (descriptor)
  473. # __objclass__ (descriptor)
  474. # __slots__ used by proxy itself
  475. # __dict__ (__getattr__)
  476. # __weakref__ (__getattr__)
  477. # __init_subclass__ (proxying metaclass not supported)
  478. # __prepare__ (metaclass)
  479. __class__ = _ProxyLookup(
  480. fallback=lambda self: type(self), is_attr=True
  481. ) # type: ignore
  482. __instancecheck__ = _ProxyLookup(lambda self, other: isinstance(other, self))
  483. __subclasscheck__ = _ProxyLookup(lambda self, other: issubclass(other, self))
  484. # __class_getitem__ triggered through __getitem__
  485. __call__ = _ProxyLookup(lambda self, *args, **kwargs: self(*args, **kwargs))
  486. __len__ = _ProxyLookup(len)
  487. __length_hint__ = _ProxyLookup(operator.length_hint)
  488. __getitem__ = _ProxyLookup(operator.getitem)
  489. __setitem__ = _ProxyLookup(operator.setitem)
  490. __delitem__ = _ProxyLookup(operator.delitem)
  491. # __missing__ triggered through __getitem__
  492. __iter__ = _ProxyLookup(iter)
  493. __next__ = _ProxyLookup(next)
  494. __reversed__ = _ProxyLookup(reversed)
  495. __contains__ = _ProxyLookup(operator.contains)
  496. __add__ = _ProxyLookup(operator.add)
  497. __sub__ = _ProxyLookup(operator.sub)
  498. __mul__ = _ProxyLookup(operator.mul)
  499. __matmul__ = _ProxyLookup(operator.matmul)
  500. __truediv__ = _ProxyLookup(operator.truediv)
  501. __floordiv__ = _ProxyLookup(operator.floordiv)
  502. __mod__ = _ProxyLookup(operator.mod)
  503. __divmod__ = _ProxyLookup(divmod)
  504. __pow__ = _ProxyLookup(pow)
  505. __lshift__ = _ProxyLookup(operator.lshift)
  506. __rshift__ = _ProxyLookup(operator.rshift)
  507. __and__ = _ProxyLookup(operator.and_)
  508. __xor__ = _ProxyLookup(operator.xor)
  509. __or__ = _ProxyLookup(operator.or_)
  510. __radd__ = _ProxyLookup(_l_to_r_op(operator.add))
  511. __rsub__ = _ProxyLookup(_l_to_r_op(operator.sub))
  512. __rmul__ = _ProxyLookup(_l_to_r_op(operator.mul))
  513. __rmatmul__ = _ProxyLookup(_l_to_r_op(operator.matmul))
  514. __rtruediv__ = _ProxyLookup(_l_to_r_op(operator.truediv))
  515. __rfloordiv__ = _ProxyLookup(_l_to_r_op(operator.floordiv))
  516. __rmod__ = _ProxyLookup(_l_to_r_op(operator.mod))
  517. __rdivmod__ = _ProxyLookup(_l_to_r_op(divmod))
  518. __rpow__ = _ProxyLookup(_l_to_r_op(pow))
  519. __rlshift__ = _ProxyLookup(_l_to_r_op(operator.lshift))
  520. __rrshift__ = _ProxyLookup(_l_to_r_op(operator.rshift))
  521. __rand__ = _ProxyLookup(_l_to_r_op(operator.and_))
  522. __rxor__ = _ProxyLookup(_l_to_r_op(operator.xor))
  523. __ror__ = _ProxyLookup(_l_to_r_op(operator.or_))
  524. __iadd__ = _ProxyIOp(operator.iadd)
  525. __isub__ = _ProxyIOp(operator.isub)
  526. __imul__ = _ProxyIOp(operator.imul)
  527. __imatmul__ = _ProxyIOp(operator.imatmul)
  528. __itruediv__ = _ProxyIOp(operator.itruediv)
  529. __ifloordiv__ = _ProxyIOp(operator.ifloordiv)
  530. __imod__ = _ProxyIOp(operator.imod)
  531. __ipow__ = _ProxyIOp(operator.ipow)
  532. __ilshift__ = _ProxyIOp(operator.ilshift)
  533. __irshift__ = _ProxyIOp(operator.irshift)
  534. __iand__ = _ProxyIOp(operator.iand)
  535. __ixor__ = _ProxyIOp(operator.ixor)
  536. __ior__ = _ProxyIOp(operator.ior)
  537. __neg__ = _ProxyLookup(operator.neg)
  538. __pos__ = _ProxyLookup(operator.pos)
  539. __abs__ = _ProxyLookup(abs)
  540. __invert__ = _ProxyLookup(operator.invert)
  541. __complex__ = _ProxyLookup(complex)
  542. __int__ = _ProxyLookup(int)
  543. __float__ = _ProxyLookup(float)
  544. __index__ = _ProxyLookup(operator.index)
  545. __round__ = _ProxyLookup(round)
  546. __trunc__ = _ProxyLookup(math.trunc)
  547. __floor__ = _ProxyLookup(math.floor)
  548. __ceil__ = _ProxyLookup(math.ceil)
  549. __enter__ = _ProxyLookup()
  550. __exit__ = _ProxyLookup()
  551. __await__ = _ProxyLookup()
  552. __aiter__ = _ProxyLookup()
  553. __anext__ = _ProxyLookup()
  554. __aenter__ = _ProxyLookup()
  555. __aexit__ = _ProxyLookup()
  556. __copy__ = _ProxyLookup(copy.copy)
  557. __deepcopy__ = _ProxyLookup(copy.deepcopy)
  558. # __getnewargs_ex__ (pickle through proxy not supported)
  559. # __getnewargs__ (pickle)
  560. # __getstate__ (pickle)
  561. # __setstate__ (pickle)
  562. # __reduce__ (pickle)
  563. # __reduce_ex__ (pickle)