local.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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 # type: ignore
  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: Call this method if the proxy is unbound instead of
  308. raising a :exc:`RuntimeError`.
  309. :param class_value: Value to return when accessed from the class.
  310. Used for ``__doc__`` so building docs still works.
  311. """
  312. __slots__ = ("bind_f", "fallback", "class_value", "name")
  313. def __init__(
  314. self,
  315. f: t.Optional[t.Callable] = None,
  316. fallback: t.Optional[t.Callable] = None,
  317. class_value: t.Optional[t.Any] = None,
  318. ) -> None:
  319. bind_f: t.Optional[t.Callable[["LocalProxy", t.Any], t.Callable]]
  320. if hasattr(f, "__get__"):
  321. # A Python function, can be turned into a bound method.
  322. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  323. return f.__get__(obj, type(obj)) # type: ignore
  324. elif f is not None:
  325. # A C function, use partial to bind the first argument.
  326. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  327. return partial(f, obj) # type: ignore
  328. else:
  329. # Use getattr, which will produce a bound method.
  330. bind_f = None
  331. self.bind_f = bind_f
  332. self.fallback = fallback
  333. self.class_value = class_value
  334. def __set_name__(self, owner: "LocalProxy", name: str) -> None:
  335. self.name = name
  336. def __get__(self, instance: "LocalProxy", owner: t.Optional[type] = None) -> t.Any:
  337. if instance is None:
  338. if self.class_value is not None:
  339. return self.class_value
  340. return self
  341. try:
  342. obj = instance._get_current_object()
  343. except RuntimeError:
  344. if self.fallback is None:
  345. raise
  346. return self.fallback.__get__(instance, owner) # type: ignore
  347. if self.bind_f is not None:
  348. return self.bind_f(instance, obj)
  349. return getattr(obj, self.name)
  350. def __repr__(self) -> str:
  351. return f"proxy {self.name}"
  352. def __call__(self, instance: "LocalProxy", *args: t.Any, **kwargs: t.Any) -> t.Any:
  353. """Support calling unbound methods from the class. For example,
  354. this happens with ``copy.copy``, which does
  355. ``type(x).__copy__(x)``. ``type(x)`` can't be proxied, so it
  356. returns the proxy type and descriptor.
  357. """
  358. return self.__get__(instance, type(instance))(*args, **kwargs)
  359. class _ProxyIOp(_ProxyLookup):
  360. """Look up an augmented assignment method on a proxied object. The
  361. method is wrapped to return the proxy instead of the object.
  362. """
  363. __slots__ = ()
  364. def __init__(
  365. self, f: t.Optional[t.Callable] = None, fallback: t.Optional[t.Callable] = None
  366. ) -> None:
  367. super().__init__(f, fallback)
  368. def bind_f(instance: "LocalProxy", obj: t.Any) -> t.Callable:
  369. def i_op(self: t.Any, other: t.Any) -> "LocalProxy":
  370. f(self, other) # type: ignore
  371. return instance
  372. return i_op.__get__(obj, type(obj)) # type: ignore
  373. self.bind_f = bind_f
  374. def _l_to_r_op(op: F) -> F:
  375. """Swap the argument order to turn an l-op into an r-op."""
  376. def r_op(obj: t.Any, other: t.Any) -> t.Any:
  377. return op(other, obj)
  378. return t.cast(F, r_op)
  379. class LocalProxy:
  380. """A proxy to the object bound to a :class:`Local`. All operations
  381. on the proxy are forwarded to the bound object. If no object is
  382. bound, a :exc:`RuntimeError` is raised.
  383. .. code-block:: python
  384. from werkzeug.local import Local
  385. l = Local()
  386. # a proxy to whatever l.user is set to
  387. user = l("user")
  388. from werkzeug.local import LocalStack
  389. _request_stack = LocalStack()
  390. # a proxy to _request_stack.top
  391. request = _request_stack()
  392. # a proxy to the session attribute of the request proxy
  393. session = LocalProxy(lambda: request.session)
  394. ``__repr__`` and ``__class__`` are forwarded, so ``repr(x)`` and
  395. ``isinstance(x, cls)`` will look like the proxied object. Use
  396. ``issubclass(type(x), LocalProxy)`` to check if an object is a
  397. proxy.
  398. .. code-block:: python
  399. repr(user) # <User admin>
  400. isinstance(user, User) # True
  401. issubclass(type(user), LocalProxy) # True
  402. :param local: The :class:`Local` or callable that provides the
  403. proxied object.
  404. :param name: The attribute name to look up on a :class:`Local`. Not
  405. used if a callable is given.
  406. .. versionchanged:: 2.0
  407. Updated proxied attributes and methods to reflect the current
  408. data model.
  409. .. versionchanged:: 0.6.1
  410. The class can be instantiated with a callable.
  411. """
  412. __slots__ = ("__local", "__name", "__wrapped__")
  413. def __init__(
  414. self,
  415. local: t.Union["Local", t.Callable[[], t.Any]],
  416. name: t.Optional[str] = None,
  417. ) -> None:
  418. object.__setattr__(self, "_LocalProxy__local", local)
  419. object.__setattr__(self, "_LocalProxy__name", name)
  420. if callable(local) and not hasattr(local, "__release_local__"):
  421. # "local" is a callable that is not an instance of Local or
  422. # LocalManager: mark it as a wrapped function.
  423. object.__setattr__(self, "__wrapped__", local)
  424. def _get_current_object(self) -> t.Any:
  425. """Return the current object. This is useful if you want the real
  426. object behind the proxy at a time for performance reasons or because
  427. you want to pass the object into a different context.
  428. """
  429. if not hasattr(self.__local, "__release_local__"): # type: ignore
  430. return self.__local() # type: ignore
  431. try:
  432. return getattr(self.__local, self.__name) # type: ignore
  433. except AttributeError:
  434. name = self.__name # type: ignore
  435. raise RuntimeError(f"no object bound to {name}") from None
  436. __doc__ = _ProxyLookup( # type: ignore
  437. class_value=__doc__, fallback=lambda self: type(self).__doc__
  438. )
  439. # __del__ should only delete the proxy
  440. __repr__ = _ProxyLookup( # type: ignore
  441. repr, fallback=lambda self: f"<{type(self).__name__} unbound>"
  442. )
  443. __str__ = _ProxyLookup(str) # type: ignore
  444. __bytes__ = _ProxyLookup(bytes)
  445. __format__ = _ProxyLookup() # type: ignore
  446. __lt__ = _ProxyLookup(operator.lt)
  447. __le__ = _ProxyLookup(operator.le)
  448. __eq__ = _ProxyLookup(operator.eq) # type: ignore
  449. __ne__ = _ProxyLookup(operator.ne) # type: ignore
  450. __gt__ = _ProxyLookup(operator.gt)
  451. __ge__ = _ProxyLookup(operator.ge)
  452. __hash__ = _ProxyLookup(hash) # type: ignore
  453. __bool__ = _ProxyLookup(bool, fallback=lambda self: False)
  454. __getattr__ = _ProxyLookup(getattr)
  455. # __getattribute__ triggered through __getattr__
  456. __setattr__ = _ProxyLookup(setattr) # type: ignore
  457. __delattr__ = _ProxyLookup(delattr) # type: ignore
  458. __dir__ = _ProxyLookup(dir, fallback=lambda self: []) # type: ignore
  459. # __get__ (proxying descriptor not supported)
  460. # __set__ (descriptor)
  461. # __delete__ (descriptor)
  462. # __set_name__ (descriptor)
  463. # __objclass__ (descriptor)
  464. # __slots__ used by proxy itself
  465. # __dict__ (__getattr__)
  466. # __weakref__ (__getattr__)
  467. # __init_subclass__ (proxying metaclass not supported)
  468. # __prepare__ (metaclass)
  469. __class__ = _ProxyLookup(fallback=lambda self: type(self)) # type: ignore
  470. __instancecheck__ = _ProxyLookup(lambda self, other: isinstance(other, self))
  471. __subclasscheck__ = _ProxyLookup(lambda self, other: issubclass(other, self))
  472. # __class_getitem__ triggered through __getitem__
  473. __call__ = _ProxyLookup(lambda self, *args, **kwargs: self(*args, **kwargs))
  474. __len__ = _ProxyLookup(len)
  475. __length_hint__ = _ProxyLookup(operator.length_hint)
  476. __getitem__ = _ProxyLookup(operator.getitem)
  477. __setitem__ = _ProxyLookup(operator.setitem)
  478. __delitem__ = _ProxyLookup(operator.delitem)
  479. # __missing__ triggered through __getitem__
  480. __iter__ = _ProxyLookup(iter)
  481. __next__ = _ProxyLookup(next)
  482. __reversed__ = _ProxyLookup(reversed)
  483. __contains__ = _ProxyLookup(operator.contains)
  484. __add__ = _ProxyLookup(operator.add)
  485. __sub__ = _ProxyLookup(operator.sub)
  486. __mul__ = _ProxyLookup(operator.mul)
  487. __matmul__ = _ProxyLookup(operator.matmul)
  488. __truediv__ = _ProxyLookup(operator.truediv)
  489. __floordiv__ = _ProxyLookup(operator.floordiv)
  490. __mod__ = _ProxyLookup(operator.mod)
  491. __divmod__ = _ProxyLookup(divmod)
  492. __pow__ = _ProxyLookup(pow)
  493. __lshift__ = _ProxyLookup(operator.lshift)
  494. __rshift__ = _ProxyLookup(operator.rshift)
  495. __and__ = _ProxyLookup(operator.and_)
  496. __xor__ = _ProxyLookup(operator.xor)
  497. __or__ = _ProxyLookup(operator.or_)
  498. __radd__ = _ProxyLookup(_l_to_r_op(operator.add))
  499. __rsub__ = _ProxyLookup(_l_to_r_op(operator.sub))
  500. __rmul__ = _ProxyLookup(_l_to_r_op(operator.mul))
  501. __rmatmul__ = _ProxyLookup(_l_to_r_op(operator.matmul))
  502. __rtruediv__ = _ProxyLookup(_l_to_r_op(operator.truediv))
  503. __rfloordiv__ = _ProxyLookup(_l_to_r_op(operator.floordiv))
  504. __rmod__ = _ProxyLookup(_l_to_r_op(operator.mod))
  505. __rdivmod__ = _ProxyLookup(_l_to_r_op(divmod))
  506. __rpow__ = _ProxyLookup(_l_to_r_op(pow))
  507. __rlshift__ = _ProxyLookup(_l_to_r_op(operator.lshift))
  508. __rrshift__ = _ProxyLookup(_l_to_r_op(operator.rshift))
  509. __rand__ = _ProxyLookup(_l_to_r_op(operator.and_))
  510. __rxor__ = _ProxyLookup(_l_to_r_op(operator.xor))
  511. __ror__ = _ProxyLookup(_l_to_r_op(operator.or_))
  512. __iadd__ = _ProxyIOp(operator.iadd)
  513. __isub__ = _ProxyIOp(operator.isub)
  514. __imul__ = _ProxyIOp(operator.imul)
  515. __imatmul__ = _ProxyIOp(operator.imatmul)
  516. __itruediv__ = _ProxyIOp(operator.itruediv)
  517. __ifloordiv__ = _ProxyIOp(operator.ifloordiv)
  518. __imod__ = _ProxyIOp(operator.imod)
  519. __ipow__ = _ProxyIOp(operator.ipow)
  520. __ilshift__ = _ProxyIOp(operator.ilshift)
  521. __irshift__ = _ProxyIOp(operator.irshift)
  522. __iand__ = _ProxyIOp(operator.iand)
  523. __ixor__ = _ProxyIOp(operator.ixor)
  524. __ior__ = _ProxyIOp(operator.ior)
  525. __neg__ = _ProxyLookup(operator.neg)
  526. __pos__ = _ProxyLookup(operator.pos)
  527. __abs__ = _ProxyLookup(abs)
  528. __invert__ = _ProxyLookup(operator.invert)
  529. __complex__ = _ProxyLookup(complex)
  530. __int__ = _ProxyLookup(int)
  531. __float__ = _ProxyLookup(float)
  532. __index__ = _ProxyLookup(operator.index)
  533. __round__ = _ProxyLookup(round)
  534. __trunc__ = _ProxyLookup(math.trunc)
  535. __floor__ = _ProxyLookup(math.floor)
  536. __ceil__ = _ProxyLookup(math.ceil)
  537. __enter__ = _ProxyLookup()
  538. __exit__ = _ProxyLookup()
  539. __await__ = _ProxyLookup()
  540. __aiter__ = _ProxyLookup()
  541. __anext__ = _ProxyLookup()
  542. __aenter__ = _ProxyLookup()
  543. __aexit__ = _ProxyLookup()
  544. __copy__ = _ProxyLookup(copy.copy)
  545. __deepcopy__ = _ProxyLookup(copy.deepcopy)
  546. # __getnewargs_ex__ (pickle through proxy not supported)
  547. # __getnewargs__ (pickle)
  548. # __getstate__ (pickle)
  549. # __setstate__ (pickle)
  550. # __reduce__ (pickle)
  551. # __reduce_ex__ (pickle)