local.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. from __future__ import annotations
  2. import copy
  3. import math
  4. import operator
  5. import typing as t
  6. from contextvars import ContextVar
  7. from functools import partial
  8. from functools import update_wrapper
  9. from operator import attrgetter
  10. from .wsgi import ClosingIterator
  11. if t.TYPE_CHECKING:
  12. from _typeshed.wsgi import StartResponse
  13. from _typeshed.wsgi import WSGIApplication
  14. from _typeshed.wsgi import WSGIEnvironment
  15. T = t.TypeVar("T")
  16. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  17. def release_local(local: Local | LocalStack) -> None:
  18. """Release the data for the current context in a :class:`Local` or
  19. :class:`LocalStack` without using a :class:`LocalManager`.
  20. This should not be needed for modern use cases, and may be removed
  21. in the future.
  22. .. versionadded:: 0.6.1
  23. """
  24. local.__release_local__()
  25. class Local:
  26. """Create a namespace of context-local data. This wraps a
  27. :class:`ContextVar` containing a :class:`dict` value.
  28. This may incur a performance penalty compared to using individual
  29. context vars, as it has to copy data to avoid mutating the dict
  30. between nested contexts.
  31. :param context_var: The :class:`~contextvars.ContextVar` to use as
  32. storage for this local. If not given, one will be created.
  33. Context vars not created at the global scope may interfere with
  34. garbage collection.
  35. .. versionchanged:: 2.0
  36. Uses ``ContextVar`` instead of a custom storage implementation.
  37. """
  38. __slots__ = ("__storage",)
  39. def __init__(self, context_var: ContextVar[dict[str, t.Any]] | None = None) -> None:
  40. if context_var is None:
  41. # A ContextVar not created at global scope interferes with
  42. # Python's garbage collection. However, a local only makes
  43. # sense defined at the global scope as well, in which case
  44. # the GC issue doesn't seem relevant.
  45. context_var = ContextVar(f"werkzeug.Local<{id(self)}>.storage")
  46. object.__setattr__(self, "_Local__storage", context_var)
  47. def __iter__(self) -> t.Iterator[tuple[str, t.Any]]:
  48. return iter(self.__storage.get({}).items())
  49. def __call__(self, name: str, *, unbound_message: str | None = None) -> LocalProxy:
  50. """Create a :class:`LocalProxy` that access an attribute on this
  51. local namespace.
  52. :param name: Proxy this attribute.
  53. :param unbound_message: The error message that the proxy will
  54. show if the attribute isn't set.
  55. """
  56. return LocalProxy(self, name, unbound_message=unbound_message)
  57. def __release_local__(self) -> None:
  58. self.__storage.set({})
  59. def __getattr__(self, name: str) -> t.Any:
  60. values = self.__storage.get({})
  61. if name in values:
  62. return values[name]
  63. raise AttributeError(name)
  64. def __setattr__(self, name: str, value: t.Any) -> None:
  65. values = self.__storage.get({}).copy()
  66. values[name] = value
  67. self.__storage.set(values)
  68. def __delattr__(self, name: str) -> None:
  69. values = self.__storage.get({})
  70. if name in values:
  71. values = values.copy()
  72. del values[name]
  73. self.__storage.set(values)
  74. else:
  75. raise AttributeError(name)
  76. class LocalStack(t.Generic[T]):
  77. """Create a stack of context-local data. This wraps a
  78. :class:`ContextVar` containing a :class:`list` value.
  79. This may incur a performance penalty compared to using individual
  80. context vars, as it has to copy data to avoid mutating the list
  81. between nested contexts.
  82. :param context_var: The :class:`~contextvars.ContextVar` to use as
  83. storage for this local. If not given, one will be created.
  84. Context vars not created at the global scope may interfere with
  85. garbage collection.
  86. .. versionchanged:: 2.0
  87. Uses ``ContextVar`` instead of a custom storage implementation.
  88. .. versionadded:: 0.6.1
  89. """
  90. __slots__ = ("_storage",)
  91. def __init__(self, context_var: ContextVar[list[T]] | None = None) -> None:
  92. if context_var is None:
  93. # A ContextVar not created at global scope interferes with
  94. # Python's garbage collection. However, a local only makes
  95. # sense defined at the global scope as well, in which case
  96. # the GC issue doesn't seem relevant.
  97. context_var = ContextVar(f"werkzeug.LocalStack<{id(self)}>.storage")
  98. self._storage = context_var
  99. def __release_local__(self) -> None:
  100. self._storage.set([])
  101. def push(self, obj: T) -> list[T]:
  102. """Add a new item to the top of the stack."""
  103. stack = self._storage.get([]).copy()
  104. stack.append(obj)
  105. self._storage.set(stack)
  106. return stack
  107. def pop(self) -> T | None:
  108. """Remove the top item from the stack and return it. If the
  109. stack is empty, return ``None``.
  110. """
  111. stack = self._storage.get([])
  112. if len(stack) == 0:
  113. return None
  114. rv = stack[-1]
  115. self._storage.set(stack[:-1])
  116. return rv
  117. @property
  118. def top(self) -> T | None:
  119. """The topmost item on the stack. If the stack is empty,
  120. `None` is returned.
  121. """
  122. stack = self._storage.get([])
  123. if len(stack) == 0:
  124. return None
  125. return stack[-1]
  126. def __call__(
  127. self, name: str | None = None, *, unbound_message: str | None = None
  128. ) -> LocalProxy:
  129. """Create a :class:`LocalProxy` that accesses the top of this
  130. local stack.
  131. :param name: If given, the proxy access this attribute of the
  132. top item, rather than the item itself.
  133. :param unbound_message: The error message that the proxy will
  134. show if the stack is empty.
  135. """
  136. return LocalProxy(self, name, unbound_message=unbound_message)
  137. class LocalManager:
  138. """Manage releasing the data for the current context in one or more
  139. :class:`Local` and :class:`LocalStack` objects.
  140. This should not be needed for modern use cases, and may be removed
  141. in the future.
  142. :param locals: A local or list of locals to manage.
  143. .. versionchanged:: 2.1
  144. The ``ident_func`` was removed.
  145. .. versionchanged:: 0.7
  146. The ``ident_func`` parameter was added.
  147. .. versionchanged:: 0.6.1
  148. The :func:`release_local` function can be used instead of a
  149. manager.
  150. """
  151. __slots__ = ("locals",)
  152. def __init__(
  153. self,
  154. locals: None | (Local | LocalStack | t.Iterable[Local | LocalStack]) = None,
  155. ) -> None:
  156. if locals is None:
  157. self.locals = []
  158. elif isinstance(locals, Local):
  159. self.locals = [locals]
  160. else:
  161. self.locals = list(locals) # type: ignore[arg-type]
  162. def cleanup(self) -> None:
  163. """Release the data in the locals for this context. Call this at
  164. the end of each request or use :meth:`make_middleware`.
  165. """
  166. for local in self.locals:
  167. release_local(local)
  168. def make_middleware(self, app: WSGIApplication) -> WSGIApplication:
  169. """Wrap a WSGI application so that local data is released
  170. automatically after the response has been sent for a request.
  171. """
  172. def application(
  173. environ: WSGIEnvironment, start_response: StartResponse
  174. ) -> t.Iterable[bytes]:
  175. return ClosingIterator(app(environ, start_response), self.cleanup)
  176. return application
  177. def middleware(self, func: WSGIApplication) -> WSGIApplication:
  178. """Like :meth:`make_middleware` but used as a decorator on the
  179. WSGI application function.
  180. .. code-block:: python
  181. @manager.middleware
  182. def application(environ, start_response):
  183. ...
  184. """
  185. return update_wrapper(self.make_middleware(func), func)
  186. def __repr__(self) -> str:
  187. return f"<{type(self).__name__} storages: {len(self.locals)}>"
  188. class _ProxyLookup:
  189. """Descriptor that handles proxied attribute lookup for
  190. :class:`LocalProxy`.
  191. :param f: The built-in function this attribute is accessed through.
  192. Instead of looking up the special method, the function call
  193. is redone on the object.
  194. :param fallback: Return this function if the proxy is unbound
  195. instead of raising a :exc:`RuntimeError`.
  196. :param is_attr: This proxied name is an attribute, not a function.
  197. Call the fallback immediately to get the value.
  198. :param class_value: Value to return when accessed from the
  199. ``LocalProxy`` class directly. Used for ``__doc__`` so building
  200. docs still works.
  201. """
  202. __slots__ = ("bind_f", "fallback", "is_attr", "class_value", "name")
  203. def __init__(
  204. self,
  205. f: t.Callable | None = None,
  206. fallback: t.Callable | None = None,
  207. class_value: t.Any | None = None,
  208. is_attr: bool = False,
  209. ) -> None:
  210. bind_f: t.Callable[[LocalProxy, t.Any], t.Callable] | None
  211. if hasattr(f, "__get__"):
  212. # A Python function, can be turned into a bound method.
  213. def bind_f(instance: LocalProxy, obj: t.Any) -> t.Callable:
  214. return f.__get__(obj, type(obj)) # type: ignore
  215. elif f is not None:
  216. # A C function, use partial to bind the first argument.
  217. def bind_f(instance: LocalProxy, obj: t.Any) -> t.Callable:
  218. return partial(f, obj)
  219. else:
  220. # Use getattr, which will produce a bound method.
  221. bind_f = None
  222. self.bind_f = bind_f
  223. self.fallback = fallback
  224. self.class_value = class_value
  225. self.is_attr = is_attr
  226. def __set_name__(self, owner: LocalProxy, name: str) -> None:
  227. self.name = name
  228. def __get__(self, instance: LocalProxy, owner: type | None = None) -> t.Any:
  229. if instance is None:
  230. if self.class_value is not None:
  231. return self.class_value
  232. return self
  233. try:
  234. obj = instance._get_current_object()
  235. except RuntimeError:
  236. if self.fallback is None:
  237. raise
  238. fallback = self.fallback.__get__(instance, owner)
  239. if self.is_attr:
  240. # __class__ and __doc__ are attributes, not methods.
  241. # Call the fallback to get the value.
  242. return fallback()
  243. return fallback
  244. if self.bind_f is not None:
  245. return self.bind_f(instance, obj)
  246. return getattr(obj, self.name)
  247. def __repr__(self) -> str:
  248. return f"proxy {self.name}"
  249. def __call__(self, instance: LocalProxy, *args: t.Any, **kwargs: t.Any) -> t.Any:
  250. """Support calling unbound methods from the class. For example,
  251. this happens with ``copy.copy``, which does
  252. ``type(x).__copy__(x)``. ``type(x)`` can't be proxied, so it
  253. returns the proxy type and descriptor.
  254. """
  255. return self.__get__(instance, type(instance))(*args, **kwargs)
  256. class _ProxyIOp(_ProxyLookup):
  257. """Look up an augmented assignment method on a proxied object. The
  258. method is wrapped to return the proxy instead of the object.
  259. """
  260. __slots__ = ()
  261. def __init__(
  262. self, f: t.Callable | None = None, fallback: t.Callable | None = None
  263. ) -> None:
  264. super().__init__(f, fallback)
  265. def bind_f(instance: LocalProxy, obj: t.Any) -> t.Callable:
  266. def i_op(self: t.Any, other: t.Any) -> LocalProxy:
  267. f(self, other) # type: ignore
  268. return instance
  269. return i_op.__get__(obj, type(obj)) # type: ignore
  270. self.bind_f = bind_f
  271. def _l_to_r_op(op: F) -> F:
  272. """Swap the argument order to turn an l-op into an r-op."""
  273. def r_op(obj: t.Any, other: t.Any) -> t.Any:
  274. return op(other, obj)
  275. return t.cast(F, r_op)
  276. def _identity(o: T) -> T:
  277. return o
  278. class LocalProxy(t.Generic[T]):
  279. """A proxy to the object bound to a context-local object. All
  280. operations on the proxy are forwarded to the bound object. If no
  281. object is bound, a ``RuntimeError`` is raised.
  282. :param local: The context-local object that provides the proxied
  283. object.
  284. :param name: Proxy this attribute from the proxied object.
  285. :param unbound_message: The error message to show if the
  286. context-local object is unbound.
  287. Proxy a :class:`~contextvars.ContextVar` to make it easier to
  288. access. Pass a name to proxy that attribute.
  289. .. code-block:: python
  290. _request_var = ContextVar("request")
  291. request = LocalProxy(_request_var)
  292. session = LocalProxy(_request_var, "session")
  293. Proxy an attribute on a :class:`Local` namespace by calling the
  294. local with the attribute name:
  295. .. code-block:: python
  296. data = Local()
  297. user = data("user")
  298. Proxy the top item on a :class:`LocalStack` by calling the local.
  299. Pass a name to proxy that attribute.
  300. .. code-block::
  301. app_stack = LocalStack()
  302. current_app = app_stack()
  303. g = app_stack("g")
  304. Pass a function to proxy the return value from that function. This
  305. was previously used to access attributes of local objects before
  306. that was supported directly.
  307. .. code-block:: python
  308. session = LocalProxy(lambda: request.session)
  309. ``__repr__`` and ``__class__`` are proxied, so ``repr(x)`` and
  310. ``isinstance(x, cls)`` will look like the proxied object. Use
  311. ``issubclass(type(x), LocalProxy)`` to check if an object is a
  312. proxy.
  313. .. code-block:: python
  314. repr(user) # <User admin>
  315. isinstance(user, User) # True
  316. issubclass(type(user), LocalProxy) # True
  317. .. versionchanged:: 2.2.2
  318. ``__wrapped__`` is set when wrapping an object, not only when
  319. wrapping a function, to prevent doctest from failing.
  320. .. versionchanged:: 2.2
  321. Can proxy a ``ContextVar`` or ``LocalStack`` directly.
  322. .. versionchanged:: 2.2
  323. The ``name`` parameter can be used with any proxied object, not
  324. only ``Local``.
  325. .. versionchanged:: 2.2
  326. Added the ``unbound_message`` parameter.
  327. .. versionchanged:: 2.0
  328. Updated proxied attributes and methods to reflect the current
  329. data model.
  330. .. versionchanged:: 0.6.1
  331. The class can be instantiated with a callable.
  332. """
  333. __slots__ = ("__wrapped", "_get_current_object")
  334. _get_current_object: t.Callable[[], T]
  335. """Return the current object this proxy is bound to. If the proxy is
  336. unbound, this raises a ``RuntimeError``.
  337. This should be used if you need to pass the object to something that
  338. doesn't understand the proxy. It can also be useful for performance
  339. if you are accessing the object multiple times in a function, rather
  340. than going through the proxy multiple times.
  341. """
  342. def __init__(
  343. self,
  344. local: ContextVar[T] | Local | LocalStack[T] | t.Callable[[], T],
  345. name: str | None = None,
  346. *,
  347. unbound_message: str | None = None,
  348. ) -> None:
  349. if name is None:
  350. get_name = _identity
  351. else:
  352. get_name = attrgetter(name) # type: ignore[assignment]
  353. if unbound_message is None:
  354. unbound_message = "object is not bound"
  355. if isinstance(local, Local):
  356. if name is None:
  357. raise TypeError("'name' is required when proxying a 'Local' object.")
  358. def _get_current_object() -> T:
  359. try:
  360. return get_name(local) # type: ignore[return-value]
  361. except AttributeError:
  362. raise RuntimeError(unbound_message) from None
  363. elif isinstance(local, LocalStack):
  364. def _get_current_object() -> T:
  365. obj = local.top
  366. if obj is None:
  367. raise RuntimeError(unbound_message)
  368. return get_name(obj)
  369. elif isinstance(local, ContextVar):
  370. def _get_current_object() -> T:
  371. try:
  372. obj = local.get()
  373. except LookupError:
  374. raise RuntimeError(unbound_message) from None
  375. return get_name(obj)
  376. elif callable(local):
  377. def _get_current_object() -> T:
  378. return get_name(local())
  379. else:
  380. raise TypeError(f"Don't know how to proxy '{type(local)}'.")
  381. object.__setattr__(self, "_LocalProxy__wrapped", local)
  382. object.__setattr__(self, "_get_current_object", _get_current_object)
  383. __doc__ = _ProxyLookup( # type: ignore
  384. class_value=__doc__, fallback=lambda self: type(self).__doc__, is_attr=True
  385. )
  386. __wrapped__ = _ProxyLookup(
  387. fallback=lambda self: self._LocalProxy__wrapped, is_attr=True
  388. )
  389. # __del__ should only delete the proxy
  390. __repr__ = _ProxyLookup( # type: ignore
  391. repr, fallback=lambda self: f"<{type(self).__name__} unbound>"
  392. )
  393. __str__ = _ProxyLookup(str) # type: ignore
  394. __bytes__ = _ProxyLookup(bytes)
  395. __format__ = _ProxyLookup() # type: ignore
  396. __lt__ = _ProxyLookup(operator.lt)
  397. __le__ = _ProxyLookup(operator.le)
  398. __eq__ = _ProxyLookup(operator.eq) # type: ignore
  399. __ne__ = _ProxyLookup(operator.ne) # type: ignore
  400. __gt__ = _ProxyLookup(operator.gt)
  401. __ge__ = _ProxyLookup(operator.ge)
  402. __hash__ = _ProxyLookup(hash) # type: ignore
  403. __bool__ = _ProxyLookup(bool, fallback=lambda self: False)
  404. __getattr__ = _ProxyLookup(getattr)
  405. # __getattribute__ triggered through __getattr__
  406. __setattr__ = _ProxyLookup(setattr) # type: ignore
  407. __delattr__ = _ProxyLookup(delattr) # type: ignore
  408. __dir__ = _ProxyLookup(dir, fallback=lambda self: []) # type: ignore
  409. # __get__ (proxying descriptor not supported)
  410. # __set__ (descriptor)
  411. # __delete__ (descriptor)
  412. # __set_name__ (descriptor)
  413. # __objclass__ (descriptor)
  414. # __slots__ used by proxy itself
  415. # __dict__ (__getattr__)
  416. # __weakref__ (__getattr__)
  417. # __init_subclass__ (proxying metaclass not supported)
  418. # __prepare__ (metaclass)
  419. __class__ = _ProxyLookup(fallback=lambda self: type(self), is_attr=True) # type: ignore[assignment]
  420. __instancecheck__ = _ProxyLookup(lambda self, other: isinstance(other, self))
  421. __subclasscheck__ = _ProxyLookup(lambda self, other: issubclass(other, self))
  422. # __class_getitem__ triggered through __getitem__
  423. __call__ = _ProxyLookup(lambda self, *args, **kwargs: self(*args, **kwargs))
  424. __len__ = _ProxyLookup(len)
  425. __length_hint__ = _ProxyLookup(operator.length_hint)
  426. __getitem__ = _ProxyLookup(operator.getitem)
  427. __setitem__ = _ProxyLookup(operator.setitem)
  428. __delitem__ = _ProxyLookup(operator.delitem)
  429. # __missing__ triggered through __getitem__
  430. __iter__ = _ProxyLookup(iter)
  431. __next__ = _ProxyLookup(next)
  432. __reversed__ = _ProxyLookup(reversed)
  433. __contains__ = _ProxyLookup(operator.contains)
  434. __add__ = _ProxyLookup(operator.add)
  435. __sub__ = _ProxyLookup(operator.sub)
  436. __mul__ = _ProxyLookup(operator.mul)
  437. __matmul__ = _ProxyLookup(operator.matmul)
  438. __truediv__ = _ProxyLookup(operator.truediv)
  439. __floordiv__ = _ProxyLookup(operator.floordiv)
  440. __mod__ = _ProxyLookup(operator.mod)
  441. __divmod__ = _ProxyLookup(divmod)
  442. __pow__ = _ProxyLookup(pow)
  443. __lshift__ = _ProxyLookup(operator.lshift)
  444. __rshift__ = _ProxyLookup(operator.rshift)
  445. __and__ = _ProxyLookup(operator.and_)
  446. __xor__ = _ProxyLookup(operator.xor)
  447. __or__ = _ProxyLookup(operator.or_)
  448. __radd__ = _ProxyLookup(_l_to_r_op(operator.add))
  449. __rsub__ = _ProxyLookup(_l_to_r_op(operator.sub))
  450. __rmul__ = _ProxyLookup(_l_to_r_op(operator.mul))
  451. __rmatmul__ = _ProxyLookup(_l_to_r_op(operator.matmul))
  452. __rtruediv__ = _ProxyLookup(_l_to_r_op(operator.truediv))
  453. __rfloordiv__ = _ProxyLookup(_l_to_r_op(operator.floordiv))
  454. __rmod__ = _ProxyLookup(_l_to_r_op(operator.mod))
  455. __rdivmod__ = _ProxyLookup(_l_to_r_op(divmod))
  456. __rpow__ = _ProxyLookup(_l_to_r_op(pow))
  457. __rlshift__ = _ProxyLookup(_l_to_r_op(operator.lshift))
  458. __rrshift__ = _ProxyLookup(_l_to_r_op(operator.rshift))
  459. __rand__ = _ProxyLookup(_l_to_r_op(operator.and_))
  460. __rxor__ = _ProxyLookup(_l_to_r_op(operator.xor))
  461. __ror__ = _ProxyLookup(_l_to_r_op(operator.or_))
  462. __iadd__ = _ProxyIOp(operator.iadd)
  463. __isub__ = _ProxyIOp(operator.isub)
  464. __imul__ = _ProxyIOp(operator.imul)
  465. __imatmul__ = _ProxyIOp(operator.imatmul)
  466. __itruediv__ = _ProxyIOp(operator.itruediv)
  467. __ifloordiv__ = _ProxyIOp(operator.ifloordiv)
  468. __imod__ = _ProxyIOp(operator.imod)
  469. __ipow__ = _ProxyIOp(operator.ipow)
  470. __ilshift__ = _ProxyIOp(operator.ilshift)
  471. __irshift__ = _ProxyIOp(operator.irshift)
  472. __iand__ = _ProxyIOp(operator.iand)
  473. __ixor__ = _ProxyIOp(operator.ixor)
  474. __ior__ = _ProxyIOp(operator.ior)
  475. __neg__ = _ProxyLookup(operator.neg)
  476. __pos__ = _ProxyLookup(operator.pos)
  477. __abs__ = _ProxyLookup(abs)
  478. __invert__ = _ProxyLookup(operator.invert)
  479. __complex__ = _ProxyLookup(complex)
  480. __int__ = _ProxyLookup(int)
  481. __float__ = _ProxyLookup(float)
  482. __index__ = _ProxyLookup(operator.index)
  483. __round__ = _ProxyLookup(round)
  484. __trunc__ = _ProxyLookup(math.trunc)
  485. __floor__ = _ProxyLookup(math.floor)
  486. __ceil__ = _ProxyLookup(math.ceil)
  487. __enter__ = _ProxyLookup()
  488. __exit__ = _ProxyLookup()
  489. __await__ = _ProxyLookup()
  490. __aiter__ = _ProxyLookup()
  491. __anext__ = _ProxyLookup()
  492. __aenter__ = _ProxyLookup()
  493. __aexit__ = _ProxyLookup()
  494. __copy__ = _ProxyLookup(copy.copy)
  495. __deepcopy__ = _ProxyLookup(copy.deepcopy)
  496. # __getnewargs_ex__ (pickle through proxy not supported)
  497. # __getnewargs__ (pickle)
  498. # __getstate__ (pickle)
  499. # __setstate__ (pickle)
  500. # __reduce__ (pickle)
  501. # __reduce_ex__ (pickle)