PK!uhreturns/__init__.py# -*- coding: utf-8 -*- PK!T>returns/functions.py# -*- coding: utf-8 -*- from functools import wraps from returns.primitives.exceptions import UnwrapFailedError from returns.result import Failure, Success def is_successful(container): """ Determins if a container was successful or not. We treat container that raise ``UnwrapFailedError`` on ``.unwrap()`` not successful. """ try: container.unwrap() except UnwrapFailedError: return False else: return True def safe(function): """ Decorator to covert exception throwing function to 'Result' monad. Show be used with care, since it only catches 'Exception' subclasses. It does not catch 'BaseException' subclasses. """ @wraps(function) def decorator(*args, **kwargs): try: return Success(function(*args, **kwargs)) except Exception as exc: return Failure(exc) return decorator def pipeline(function): """ Decorator to enable 'do-notation' context. Should be used for series of computations that rely on ``.unwrap`` method. """ @wraps(function) def decorator(*args, **kwargs): try: return function(*args, **kwargs) except UnwrapFailedError as exc: return exc.halted_container return decorator PK!Zreturns/functions.pyi# -*- coding: utf-8 -*- from typing import Callable, TypeVar from returns.primitives.container import Container from returns.result import Result _ContainerType = TypeVar('_ContainerType', bound=Container) _ReturnType = TypeVar('_ReturnType') _ReturnsContainerType = TypeVar( '_ReturnsContainerType', bound=Callable[..., Container], ) def is_successful(container: _ContainerType) -> bool: ... # Typing decorators is not an easy task, see: # https://github.com/python/mypy/issues/3157 def pipeline(function: _ReturnsContainerType) -> _ReturnsContainerType: ... def safe( function: Callable[..., _ReturnType], ) -> Callable[..., Result[_ReturnType, Exception]]: ... PK!uhreturns/primitives/__init__.py# -*- coding: utf-8 -*- PK!NO\Dreturns/primitives/container.py# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Generic, TypeVar from returns.primitives.exceptions import ImmutableStateError _ValueType = TypeVar('_ValueType') _ErrorType = TypeVar('_ErrorType') class _BaseContainer(object, metaclass=ABCMeta): """Utility class to provide all needed magic methods to the contest.""" __slots__ = ('_inner_value',) def __init__(self, inner_value): """ Wraps the given value in the Container. 'value' is any arbitrary value of any type including functions. """ object.__setattr__(self, '_inner_value', inner_value) def __setattr__(self, attr_name, attr_value): """Makes inner state of the monads immutable.""" raise ImmutableStateError() def __delattr__(self, attr_name): # noqa: Z434 """Makes inner state of the monads immutable.""" raise ImmutableStateError() def __str__(self): """Converts to string.""" return '{0}: {1}'.format( self.__class__.__qualname__, str(self._inner_value), ) def __eq__(self, other): """Used to compare two 'Container' objects.""" if not isinstance(other, _BaseContainer): return False if type(self) != type(other): return False return self._inner_value == other._inner_value # noqa: Z441 class Container(_BaseContainer, metaclass=ABCMeta): """ Represents a "context" in which calculations can be executed. You won't create 'Container' instances directly. Instead, sub-classes implement specific contexts. Monads allow you to bind together a series of calculations while maintaining the context of that specific monad. This is an abstract class with the API declaration. Attributes: _inner_value: Wrapped internal immutable state. """ @abstractmethod # noqa: A003 def map(self, function): # pragma: no cover """ Applies 'function' to the contents of the functor. And returns a new functor value. Works for monads that represent success. Is the opposite of :meth:`~fix`. """ raise NotImplementedError() @abstractmethod def bind(self, function): # pragma: no cover """ Applies 'function' to the result of a previous calculation. And returns a new monad. Works for monads that represent success. Is the opposite of :meth:`~rescue`. """ raise NotImplementedError() @abstractmethod def fix(self, function): # pragma: no cover """ Applies 'function' to the contents of the functor. And returns a new functor value. Works for monads that represent failure. Is the opposite of :meth:`~map`. """ raise NotImplementedError() @abstractmethod def rescue(self, function): # pragma: no cover """ Applies 'function' to the result of a previous calculation. And returns a new monad. Works for monads that represent failure. Is the opposite of :meth:`~bind`. """ raise NotImplementedError() @abstractmethod def value_or(self, default_value): # pragma: no cover """Forces to unwrap value from monad or return a default.""" raise NotImplementedError() @abstractmethod def unwrap(self): # pragma: no cover """ Custom magic method to unwrap inner value from monad. Should be redefined for ones that actually have values. And for ones that raise an exception for no values. This method is the opposite of :meth:`~failure`. """ raise NotImplementedError() @abstractmethod def failure(self): # pragma: no cover """ Custom magic method to unwrap inner value from the failed monad. This method is the opposite of :meth:`~unwrap`. """ raise NotImplementedError() class GenericContainerOneSlot(Generic[_ValueType], Container): """ Base class for monads with one typed slot. Use this type for generic inheritance only. Use :class:`~Container` as a general type for polymorphism. """ class GenericContainerTwoSlots(Generic[_ValueType, _ErrorType], Container): """ Base class for monads with two typed slot. Use this type for generic inheritance only. Use :class:`~Container` as a general type for polymorphism. """ PK!ϖ returns/primitives/container.pyi# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Any, Generic, NoReturn, TypeVar _ValueType = TypeVar('_ValueType') _ErrorType = TypeVar('_ErrorType') class _BaseContainer(object, metaclass=ABCMeta): __slots__ = ('_inner_value',) _inner_value: Any def __setattr__(self, attr_name: str, attr_value) -> NoReturn: ... def __delattr__(self, attr_name: str) -> NoReturn: # noqa: Z434 ... def __str__(self) -> str: ... def __eq__(self, other) -> bool: ... class Container(_BaseContainer, metaclass=ABCMeta): @abstractmethod # noqa: A003 def map(self, function): ... @abstractmethod def bind(self, function): ... @abstractmethod def fix(self, function): ... @abstractmethod def rescue(self, function): ... @abstractmethod def value_or(self, default_value): ... @abstractmethod def unwrap(self): ... @abstractmethod def failure(self): ... class GenericContainerOneSlot( Generic[_ValueType], Container, metaclass=ABCMeta, ): ... class GenericContainerTwoSlots( Generic[_ValueType, _ErrorType], Container, metaclass=ABCMeta, ): ... PK!B returns/primitives/exceptions.py# -*- coding: utf-8 -*- class UnwrapFailedError(Exception): """Raised when a container can not be unwrapped into a meaningful value.""" def __init__(self, container): """ Saves halted container in the inner state. So, this container can later be unpacked from this exception and used as a regular value. """ super().__init__() self.halted_container = container class ImmutableStateError(Exception): """Raised when a container is forced to be mutated.""" PK!'@``!returns/primitives/exceptions.pyi# -*- coding: utf-8 -*- from typing import TypeVar from returns.primitives.container import Container _ContainerType = TypeVar('_ContainerType', bound=Container) class UnwrapFailedError(Exception): def __init__(self, container: _ContainerType) -> None: self.halted_container = container class ImmutableStateError(Exception): ... PK!returns/py.typedPK!P.4//returns/result.py# -*- coding: utf-8 -*- from abc import ABCMeta from typing import Any, TypeVar from returns.primitives.container import GenericContainerTwoSlots from returns.primitives.exceptions import UnwrapFailedError _ValueType = TypeVar('_ValueType') _ErrorType = TypeVar('_ErrorType') class Result( GenericContainerTwoSlots[_ValueType, _ErrorType], metaclass=ABCMeta, ): """Base class for Failure and Success.""" class Failure(Result[Any, _ErrorType]): """ Represents a calculation which has failed. It should contain an error code or message. To help with readability you may alternatively use the alias 'Failure'. """ def map(self, function): # noqa: A003 """Returns the 'Failure' instance that was used to call the method.""" return self def bind(self, function): """Returns the 'Failure' instance that was used to call the method.""" return self def fix(self, function): """ Applies function to the inner value. Applies 'function' to the contents of the 'Success' instance and returns a new 'Success' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Success(function(self._inner_value)) def rescue(self, function): """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return Result a 'Failure' or 'Success' type object. """ return function(self._inner_value) def value_or(self, default_value): """Returns the value if we deal with 'Success' or default otherwise.""" return default_value def unwrap(self): """Raises an exception, since it does not have a value inside.""" raise UnwrapFailedError(self) def failure(self): """Unwraps inner error value from failed monad.""" return self._inner_value class Success(Result[_ValueType, Any]): """ Represents a calculation which has succeeded and contains the result. To help with readability you may alternatively use the alias 'Success'. """ def map(self, function): # noqa: A003 """ Applies function to the inner value. Applies 'function' to the contents of the 'Success' instance and returns a new 'Success' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Success(function(self._inner_value)) def bind(self, function): """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return Result a 'Failure' or 'Success' type object. """ return function(self._inner_value) def fix(self, function): """Returns the 'Success' instance that was used to call the method.""" return self def rescue(self, function): """Returns the 'Success' instance that was used to call the method.""" return self def value_or(self, default_value): """Returns the value if we deal with 'Success' or default otherwise.""" return self._inner_value def unwrap(self): """Returns the unwrapped value from the inside of this monad.""" return self._inner_value def failure(self): """Raises an exception, since it does not have an error inside.""" raise UnwrapFailedError(self) PK!} returns/result.pyi# -*- coding: utf-8 -*- from abc import ABCMeta from typing import Any, Callable, NoReturn, TypeVar, Union from typing_extensions import final from returns.primitives.container import Container, GenericContainerTwoSlots _ContainerType = TypeVar('_ContainerType', bound=Container) _ResultType = TypeVar('_ResultType', bound='Result') # Regular type vars, work correctly: _ValueType = TypeVar('_ValueType') _NewValueType = TypeVar('_NewValueType') _ErrorType = TypeVar('_ErrorType') class Result( GenericContainerTwoSlots[_ValueType, _ErrorType], metaclass=ABCMeta, ): _inner_value: Union[_ValueType, _ErrorType] def map( # noqa: A003 self, function: Callable[[_ValueType], _NewValueType], ) -> Union['Success[_NewValueType]', 'Result[_ValueType, _ErrorType]']: ... def bind( self, function: Callable[[_ValueType], _ContainerType], ) -> Union[_ContainerType, 'Result[_ValueType, _ErrorType]']: ... def fix( self, function: Callable[[_ErrorType], _NewValueType], ) -> Union['Success[_ValueType]', 'Success[_NewValueType]']: ... def rescue( self, function: Callable[[_ErrorType], _ContainerType], ) -> Union[_ContainerType, 'Result[_ValueType, _ErrorType]']: ... def value_or( self, default_value: _NewValueType, ) -> Union[_NewValueType, _ValueType]: ... def unwrap(self) -> Union[NoReturn, _ValueType]: ... def failure(self) -> Union[NoReturn, _ErrorType]: ... @final class Failure(Result[Any, _ErrorType]): _inner_value: _ErrorType def __init__(self, inner_value: _ErrorType) -> None: ... def map(self, function) -> 'Failure[_ErrorType]': # noqa: A003 ... def bind(self, function) -> 'Failure[_ErrorType]': ... def fix( self, function: Callable[[_ErrorType], _NewValueType], ) -> 'Success[_NewValueType]': ... def rescue( self, function: Callable[[_ErrorType], _ContainerType], ) -> _ContainerType: ... def value_or(self, default_value: _NewValueType) -> _NewValueType: ... def unwrap(self) -> NoReturn: ... def failure(self) -> _ErrorType: ... @final class Success(Result[_ValueType, Any]): _inner_value: _ValueType def __init__(self, inner_value: _ValueType) -> None: ... def map( # noqa: A003 self, function: Callable[[_ValueType], _NewValueType], ) -> 'Success[_NewValueType]': ... def bind( self, function: Callable[[_ValueType], _ContainerType], ) -> _ContainerType: ... def fix(self, function) -> 'Success[_ValueType]': ... def rescue(self, function) -> 'Success[_ValueType]': ... def value_or(self, default_value: _NewValueType) -> _ValueType: ... def unwrap(self) -> _ValueType: ... def failure(self) -> NoReturn: ... PK!R00returns-0.4.0.dist-info/LICENSEMIT License Copyright (c) 2019 wemake.services Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HڽTUreturns-0.4.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H ' returns-0.4.0.dist-info/METADATAYks۸_l&(oIZM^o_$(Y\$I6m?U^([z/*밗OEia ^  7"M^t) Pf", 3*v"1K{T$Mfg13|$&nJC-xl'"V Nd$2}GWb1W:6Z1OXX4(oxI[."_45ɜ/ZJKYVNNJ,+DSFTka*Z^o`$9vL$*O]Zn :X7'|mbnHRұ 8yq5#.Y ȼnlX ݍ h3GmLE3,EtILex,^nhYhfE=!Ӷxr>{r#|;7=.^gד1)V'vE^{rpqw;zzt}{~x>뽻["=;ϯO_=<{ٛm^qoo;ݣO^p:}N|9κt/>wޛw󽷿mwWá3wܿ~1bދs![B&qIA˝V4HJIKA'ly4aw龜B8h{H1k(q2pWEb|`jK"/s_fݲ˭[alcUc-vdQ[e b]`(jVӮUkÝ*2H-c2(f,֦{SB# /\?d8}\!z : lFd Ul,Q©M6 VF g v^lp ܀mHzb*o7 qH72)E܉&"Vc̀1]) zaE\]~#9dЧWszkm3#L GS| ' X|`̙KukZt|9 AXXRo\D*,#P=}G5Jh|,QNuDAD7h*7ԐaK & tæc vQ"Krav:I"L8Eb:L˻:PM_,؆LEH$BPΩ _Rn m_عODɨ6^>x1W2"14fӰe^)_&*Wr/%k¿tMRTRc33#++>{Gݝ|# 9;\sW|0Ceǔ>M2)$MT6,ogJȸ"Ua.'nY <di4 eS7Ȃ aӮ9*4yBFȭBˠrs\nhJG GD@7zn<#:@ ,j31sӇ uDVG0569۠.K. T1먋-5@JIM zPcX!+ 7|Be!bb1bWtar|E#{ptWdpF9lUV ?VR\ApztyPK!H9*returns-0.4.0.dist-info/RECORD˖@}.6" "bb#-6 <}fq$3WU-]^7 ̭ ďrٌHseOt80$1=bkEtmu)Y?R59ŗJ`,2:Z[rz\CQ‡[:䡰=t~mGƋut!TI=1S|G3'444 j?  /ijca Խd݆T=>rf x;Yq.+ݦ*s4dEKZ$VP#ʳ0'rEw絹d(BrFg3cw5m25V&%:b*bd|ɾՓ##Ip`@gPK!uhreturns/__init__.pyPK!T>Ireturns/functions.pyPK!Zreturns/functions.pyiPK!uh{returns/primitives/__init__.pyPK!NO\Dreturns/primitives/container.pyPK!ϖ returns/primitives/container.pyiPK!B returns/primitives/exceptions.pyPK!'@``!7"returns/primitives/exceptions.pyiPK!#returns/py.typedPK!P.4//$returns/result.pyPK!} b2returns/result.pyiPK!R00i>returns-0.4.0.dist-info/LICENSEPK!HڽTUBreturns-0.4.0.dist-info/WHEELPK!H ' eCreturns-0.4.0.dist-info/METADATAPK!H9*cNreturns-0.4.0.dist-info/RECORDPK92Q