Advertisement
kopyl

Untitled

May 15th, 2022
809
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.85 KB | None | 0 0
  1. class LocalProxy:
  2.     """A proxy to the object bound to a :class:`Local`. All operations
  3.    on the proxy are forwarded to the bound object. If no object is
  4.    bound, a :exc:`RuntimeError` is raised.
  5.  
  6.    .. code-block:: python
  7.  
  8.        from werkzeug.local import Local
  9.        l = Local()
  10.  
  11.        # a proxy to whatever l.user is set to
  12.        user = l("user")
  13.  
  14.        from werkzeug.local import LocalStack
  15.        _request_stack = LocalStack()
  16.  
  17.        # a proxy to _request_stack.top
  18.        request = _request_stack()
  19.  
  20.        # a proxy to the session attribute of the request proxy
  21.        session = LocalProxy(lambda: request.session)
  22.  
  23.    ``__repr__`` and ``__class__`` are forwarded, so ``repr(x)`` and
  24.    ``isinstance(x, cls)`` will look like the proxied object. Use
  25.    ``issubclass(type(x), LocalProxy)`` to check if an object is a
  26.    proxy.
  27.  
  28.    .. code-block:: python
  29.  
  30.        repr(user)  # <User admin>
  31.        isinstance(user, User)  # True
  32.        issubclass(type(user), LocalProxy)  # True
  33.  
  34.    :param local: The :class:`Local` or callable that provides the
  35.        proxied object.
  36.    :param name: The attribute name to look up on a :class:`Local`. Not
  37.        used if a callable is given.
  38.  
  39.    .. versionchanged:: 2.0
  40.        Updated proxied attributes and methods to reflect the current
  41.        data model.
  42.  
  43.    .. versionchanged:: 0.6.1
  44.        The class can be instantiated with a callable.
  45.    """
  46.  
  47.     __slots__ = ("__local", "__name", "__wrapped__")
  48.  
  49.     def __init__(
  50.         self,
  51.         local: t.Union["Local", t.Callable[[], t.Any]],
  52.         name: t.Optional[str] = None,
  53.     ) -> None:
  54.         object.__setattr__(self, "_LocalProxy__local", local)
  55.         object.__setattr__(self, "_LocalProxy__name", name)
  56.  
  57.         if callable(local) and not hasattr(local, "__release_local__"):
  58.             # "local" is a callable that is not an instance of Local or
  59.             # LocalManager: mark it as a wrapped function.
  60.             object.__setattr__(self, "__wrapped__", local)
  61.  
  62.     def _get_current_object(self) -> t.Any:
  63.         """Return the current object.  This is useful if you want the real
  64.        object behind the proxy at a time for performance reasons or because
  65.        you want to pass the object into a different context.
  66.        """
  67.         if not hasattr(self.__local, "__release_local__"):  # type: ignore
  68.             return self.__local()  # type: ignore
  69.  
  70.         try:
  71.             return getattr(self.__local, self.__name)  # type: ignore
  72.         except AttributeError:
  73.             name = self.__name  # type: ignore
  74.             raise RuntimeError(f"no object bound to {name}") from None
  75.  
  76.     __doc__ = _ProxyLookup(  # type: ignore
  77.         class_value=__doc__, fallback=lambda self: type(self).__doc__, is_attr=True
  78.     )
  79.     # __del__ should only delete the proxy
  80.     __repr__ = _ProxyLookup(  # type: ignore
  81.         repr, fallback=lambda self: f"<{type(self).__name__} unbound>"
  82.     )
  83.     __str__ = _ProxyLookup(str)  # type: ignore
  84.     __bytes__ = _ProxyLookup(bytes)
  85.     __format__ = _ProxyLookup()  # type: ignore
  86.     __lt__ = _ProxyLookup(operator.lt)
  87.     __le__ = _ProxyLookup(operator.le)
  88.     __eq__ = _ProxyLookup(operator.eq)  # type: ignore
  89.     __ne__ = _ProxyLookup(operator.ne)  # type: ignore
  90.     __gt__ = _ProxyLookup(operator.gt)
  91.     __ge__ = _ProxyLookup(operator.ge)
  92.     __hash__ = _ProxyLookup(hash)  # type: ignore
  93.     __bool__ = _ProxyLookup(bool, fallback=lambda self: False)
  94.     __getattr__ = _ProxyLookup(getattr)
  95.     # __getattribute__ triggered through __getattr__
  96.     __setattr__ = _ProxyLookup(setattr)  # type: ignore
  97.     __delattr__ = _ProxyLookup(delattr)  # type: ignore
  98.     __dir__ = _ProxyLookup(dir, fallback=lambda self: [])  # type: ignore
  99.     # __get__ (proxying descriptor not supported)
  100.     # __set__ (descriptor)
  101.     # __delete__ (descriptor)
  102.     # __set_name__ (descriptor)
  103.     # __objclass__ (descriptor)
  104.     # __slots__ used by proxy itself
  105.     # __dict__ (__getattr__)
  106.     # __weakref__ (__getattr__)
  107.     # __init_subclass__ (proxying metaclass not supported)
  108.     # __prepare__ (metaclass)
  109.     __class__ = _ProxyLookup(
  110.         fallback=lambda self: type(self), is_attr=True
  111.     )  # type: ignore
  112.     __instancecheck__ = _ProxyLookup(lambda self, other: isinstance(other, self))
  113.     __subclasscheck__ = _ProxyLookup(lambda self, other: issubclass(other, self))
  114.     # __class_getitem__ triggered through __getitem__
  115.     __call__ = _ProxyLookup(lambda self, *args, **kwargs: self(*args, **kwargs))
  116.     __len__ = _ProxyLookup(len)
  117.     __length_hint__ = _ProxyLookup(operator.length_hint)
  118.     __getitem__ = _ProxyLookup(operator.getitem)
  119.     __setitem__ = _ProxyLookup(operator.setitem)
  120.     __delitem__ = _ProxyLookup(operator.delitem)
  121.     # __missing__ triggered through __getitem__
  122.     __iter__ = _ProxyLookup(iter)
  123.     __next__ = _ProxyLookup(next)
  124.     __reversed__ = _ProxyLookup(reversed)
  125.     __contains__ = _ProxyLookup(operator.contains)
  126.     __add__ = _ProxyLookup(operator.add)
  127.     __sub__ = _ProxyLookup(operator.sub)
  128.     __mul__ = _ProxyLookup(operator.mul)
  129.     __matmul__ = _ProxyLookup(operator.matmul)
  130.     __truediv__ = _ProxyLookup(operator.truediv)
  131.     __floordiv__ = _ProxyLookup(operator.floordiv)
  132.     __mod__ = _ProxyLookup(operator.mod)
  133.     __divmod__ = _ProxyLookup(divmod)
  134.     __pow__ = _ProxyLookup(pow)
  135.     __lshift__ = _ProxyLookup(operator.lshift)
  136.     __rshift__ = _ProxyLookup(operator.rshift)
  137.     __and__ = _ProxyLookup(operator.and_)
  138.     __xor__ = _ProxyLookup(operator.xor)
  139.     __or__ = _ProxyLookup(operator.or_)
  140.     __radd__ = _ProxyLookup(_l_to_r_op(operator.add))
  141.     __rsub__ = _ProxyLookup(_l_to_r_op(operator.sub))
  142.     __rmul__ = _ProxyLookup(_l_to_r_op(operator.mul))
  143.     __rmatmul__ = _ProxyLookup(_l_to_r_op(operator.matmul))
  144.     __rtruediv__ = _ProxyLookup(_l_to_r_op(operator.truediv))
  145.     __rfloordiv__ = _ProxyLookup(_l_to_r_op(operator.floordiv))
  146.     __rmod__ = _ProxyLookup(_l_to_r_op(operator.mod))
  147.     __rdivmod__ = _ProxyLookup(_l_to_r_op(divmod))
  148.     __rpow__ = _ProxyLookup(_l_to_r_op(pow))
  149.     __rlshift__ = _ProxyLookup(_l_to_r_op(operator.lshift))
  150.     __rrshift__ = _ProxyLookup(_l_to_r_op(operator.rshift))
  151.     __rand__ = _ProxyLookup(_l_to_r_op(operator.and_))
  152.     __rxor__ = _ProxyLookup(_l_to_r_op(operator.xor))
  153.     __ror__ = _ProxyLookup(_l_to_r_op(operator.or_))
  154.     __iadd__ = _ProxyIOp(operator.iadd)
  155.     __isub__ = _ProxyIOp(operator.isub)
  156.     __imul__ = _ProxyIOp(operator.imul)
  157.     __imatmul__ = _ProxyIOp(operator.imatmul)
  158.     __itruediv__ = _ProxyIOp(operator.itruediv)
  159.     __ifloordiv__ = _ProxyIOp(operator.ifloordiv)
  160.     __imod__ = _ProxyIOp(operator.imod)
  161.     __ipow__ = _ProxyIOp(operator.ipow)
  162.     __ilshift__ = _ProxyIOp(operator.ilshift)
  163.     __irshift__ = _ProxyIOp(operator.irshift)
  164.     __iand__ = _ProxyIOp(operator.iand)
  165.     __ixor__ = _ProxyIOp(operator.ixor)
  166.     __ior__ = _ProxyIOp(operator.ior)
  167.     __neg__ = _ProxyLookup(operator.neg)
  168.     __pos__ = _ProxyLookup(operator.pos)
  169.     __abs__ = _ProxyLookup(abs)
  170.     __invert__ = _ProxyLookup(operator.invert)
  171.     __complex__ = _ProxyLookup(complex)
  172.     __int__ = _ProxyLookup(int)
  173.     __float__ = _ProxyLookup(float)
  174.     __index__ = _ProxyLookup(operator.index)
  175.     __round__ = _ProxyLookup(round)
  176.     __trunc__ = _ProxyLookup(math.trunc)
  177.     __floor__ = _ProxyLookup(math.floor)
  178.     __ceil__ = _ProxyLookup(math.ceil)
  179.     __enter__ = _ProxyLookup()
  180.     __exit__ = _ProxyLookup()
  181.     __await__ = _ProxyLookup()
  182.     __aiter__ = _ProxyLookup()
  183.     __anext__ = _ProxyLookup()
  184.     __aenter__ = _ProxyLookup()
  185.     __aexit__ = _ProxyLookup()
  186.     __copy__ = _ProxyLookup(copy.copy)
  187.     __deepcopy__ = _ProxyLookup(copy.deepcopy)
  188.     # __getnewargs_ex__ (pickle through proxy not supported)
  189.     # __getnewargs__ (pickle)
  190.     # __getstate__ (pickle)
  191.     # __setstate__ (pickle)
  192.     # __reduce__ (pickle)
  193.     # __reduce_ex__ (pickle)
  194.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement