PK!uhreturns/__init__.py# -*- coding: utf-8 -*- PK!aMreturns/do_notation.py# -*- coding: utf-8 -*- from functools import wraps from typing import Callable from returns.primitives.exceptions import UnwrapFailedError from returns.primitives.types import MonadType # Typing decorators is not an easy task, see: # https://github.com/python/mypy/issues/3157 def do_notation( function: Callable[..., MonadType], ) -> Callable[..., MonadType]: """ Decorator to enable 'do-notation' context. Should be used for series of computations that rely on ``.unwrap`` method. """ @wraps(function) def decorator(*args, **kwargs) -> MonadType: try: return function(*args, **kwargs) except UnwrapFailedError as exc: return exc.halted_monad return decorator PK!dreturns/do_notation.pyi# -*- coding: utf-8 -*- from typing import Callable from returns.primitives.types import MonadType def do_notation( function: Callable[..., MonadType], ) -> Callable[..., MonadType]: ... PK!,returns/either.py# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Any, Callable, Generic, NoReturn, TypeVar, Union from typing_extensions import final from returns.primitives.exceptions import UnwrapFailedError from returns.primitives.monad import Monad, NewValueType, ValueType from returns.primitives.types import MonadType _ErrorType = TypeVar('_ErrorType') # That's the most ugly part. # We need to express `Either` with two type parameters and # Left and Right with just one parameter. # And that's how we do it. Any other and more cleaner ways are appreciated. class Either(Generic[ValueType, _ErrorType], metaclass=ABCMeta): """ Represents a calculation that may either fail or succeed. An alternative to using exceptions. 'Either' (or its alias 'Result') is an abstract type and should not be instantiated directly. Instead use 'Right' (or its alias 'Success') and 'Left' (or its alias 'Failure'). """ _inner_value: Union[ValueType, _ErrorType] @abstractmethod def unwrap(self) -> ValueType: # 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. """ raise NotImplementedError() @final class Left(Either[Any, _ErrorType], Monad[_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 __init__(self, inner_value: _ErrorType) -> None: """ 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 fmap(self, function) -> 'Left[_ErrorType]': """Returns the 'Left' instance that was used to call the method.""" return self def bind(self, function) -> 'Left[_ErrorType]': """Returns the 'Left' instance that was used to call the method.""" return self def efmap( self, function: Callable[[_ErrorType], NewValueType], ) -> 'Right[NewValueType]': """ Applies function to the inner value. Applies 'function' to the contents of the 'Right' instance and returns a new 'Right' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Right(function(self._inner_value)) def ebind(self, function: Callable[[_ErrorType], MonadType]) -> MonadType: """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return either a 'Left' or 'Right' type object. """ return function(self._inner_value) def value_or(self, default_value: NewValueType) -> NewValueType: """Returns the value if we deal with 'Right' or default if 'Left'.""" return default_value def unwrap(self) -> NoReturn: """Raises an exception, since it does not have a value inside.""" raise UnwrapFailedError(self) def failure(self) -> _ErrorType: """Unwraps inner error value from failed monad.""" return self._inner_value @final class Right(Either[ValueType, Any], Monad[ValueType]): """ Represents a calculation which has succeeded and contains the result. To help with readability you may alternatively use the alias 'Success'. """ def __init__(self, inner_value: ValueType) -> None: """ 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 fmap( self, function: Callable[[ValueType], NewValueType], ) -> 'Right[NewValueType]': """ Applies function to the inner value. Applies 'function' to the contents of the 'Right' instance and returns a new 'Right' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Right(function(self._inner_value)) def bind( self, function: Callable[[ValueType], MonadType], ) -> MonadType: """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return either a 'Left' or 'Right' type object. """ return function(self._inner_value) def efmap(self, function) -> 'Right[ValueType]': """Returns the 'Right' instance that was used to call the method.""" return self def ebind(self, function) -> 'Right[ValueType]': """Returns the 'Right' instance that was used to call the method.""" return self def value_or(self, default_value: NewValueType) -> ValueType: """Returns the value if we deal with 'Right' or default if 'Left'.""" return self._inner_value def unwrap(self) -> ValueType: """Returns the unwrapped value from the inside of this monad.""" return self._inner_value def failure(self) -> NoReturn: """Raises an exception, since it does not have an error inside.""" raise UnwrapFailedError(self) # Useful aliases for end users: Result = Either Success = Right Failure = Left PK!o"aareturns/either.pyi# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Any, Callable, Generic, NoReturn, TypeVar, Union from typing_extensions import final from returns.primitives.monad import Monad, NewValueType, ValueType # There's a wierd bug with mypy when we remove this line and use import: _MonadType = TypeVar('_MonadType', bound=Union['Monad', 'Either']) # Regular type var, works correctly: _ErrorType = TypeVar('_ErrorType') class Either(Generic[ValueType, _ErrorType], metaclass=ABCMeta): _inner_value: Union[ValueType, _ErrorType] @abstractmethod def unwrap(self) -> ValueType: # pragma: no cover ... @final class Left(Either[Any, _ErrorType], Monad[_ErrorType]): _inner_value: _ErrorType def __init__(self, inner_value: _ErrorType) -> None: ... def fmap(self, function) -> 'Left[_ErrorType]': ... def bind(self, function) -> 'Left[_ErrorType]': ... def efmap( self, function: Callable[[_ErrorType], NewValueType], ) -> 'Right[NewValueType]': ... def ebind(self, function: Callable[[_ErrorType], _MonadType]) -> _MonadType: ... def value_or(self, default_value: NewValueType) -> NewValueType: ... def unwrap(self) -> NoReturn: ... def failure(self) -> _ErrorType: ... @final class Right(Either[ValueType, Any], Monad[ValueType]): _inner_value: ValueType def __init__(self, inner_value: ValueType) -> None: ... def fmap( self, function: Callable[[ValueType], NewValueType], ) -> 'Right[NewValueType]': ... def bind( self, function: Callable[[ValueType], _MonadType], ) -> _MonadType: ... def efmap(self, function) -> 'Right[ValueType]': ... def ebind(self, function) -> 'Right[ValueType]': ... def value_or(self, default_value: NewValueType) -> ValueType: ... def unwrap(self) -> ValueType: ... def failure(self) -> NoReturn: ... # Useful aliases for end users: Result = Either Success = Right Failure = Left PK!''returns/functions.py# -*- coding: utf-8 -*- from functools import wraps from typing import Callable, TypeVar from returns.either import Either, Failure, Success from returns.primitives.exceptions import UnwrapFailedError from returns.primitives.types import MonadType _ReturnType = TypeVar('_ReturnType') def is_successful(monad: MonadType) -> bool: """Determins if a monad was a success or not.""" try: monad.unwrap() except UnwrapFailedError: return False else: return True def safe( function: Callable[..., _ReturnType], ) -> Callable[..., Either[_ReturnType, Exception]]: """ Decorator to covert exception throwing function to 'Either' monad. Show be used with care, since it only catches 'Exception' subclasses. It does not catch 'BaseException' subclasses. """ @wraps(function) def decorator(*args, **kwargs) -> Either[_ReturnType, Exception]: try: return Success(function(*args, **kwargs)) except Exception as exc: return Failure(exc) return decorator PK!U__returns/functions.pyi# -*- coding: utf-8 -*- from typing import Callable, TypeVar from returns.either import Either from returns.primitives.types import MonadType _ReturnType = TypeVar('_ReturnType') def is_successful(monad: MonadType) -> bool: ... def safe( function: Callable[..., _ReturnType], ) -> Callable[..., Either[_ReturnType, Exception]]: ... PK!^returns/maybe.py# -*- coding: utf-8 -*- from abc import ABCMeta from typing import Callable, NoReturn, Union, overload from typing_extensions import Literal, final from returns.primitives.exceptions import UnwrapFailedError from returns.primitives.monad import Monad, NewValueType, ValueType from returns.primitives.types import MonadType class Maybe(Monad[ValueType], metaclass=ABCMeta): """ Represents a result of a series of commutation that can return ``None``. An alternative to using exceptions. ``Maybe`` is an abstract type and should not be instantiated directly. Instead use ``Some`` and ``Nothing``. """ @overload @classmethod def new(cls, inner_value: Literal[None]) -> 'Nothing': # type: ignore """Overload to declare correct return type for Nothing.""" @overload # noqa: F811 @classmethod def new(cls, inner_value: ValueType) -> 'Some[ValueType]': """Overload to declare correct return type for Some.""" @classmethod # noqa: F811 def new( cls, inner_value: Union[ValueType, Literal[None]], ) -> Union['Nothing', 'Some[ValueType]']: """Creates new instance of Some or Nothing monads based on a value.""" if inner_value is None: return Nothing(inner_value) return Some(inner_value) @final class Nothing(Maybe[Literal[None]]): """Represents an empty state.""" _inner_value: Literal[None] def __init__(self, inner_value: Literal[None] = None) -> None: """ Wraps the given value in the Container. 'value' can only be ``None``. """ object.__setattr__(self, '_inner_value', inner_value) def fmap(self, function) -> 'Nothing': """Returns the 'Nothing' instance that was used to call the method.""" return self def bind(self, function) -> 'Nothing': """Returns the 'Nothing' instance that was used to call the method.""" return self def efmap( self, function: Callable[[Literal[None]], 'NewValueType'], ) -> 'Some[NewValueType]': """ Applies function to the inner value. Applies 'function' to the contents of the 'Some' instance and returns a new 'Some' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Some(function(self._inner_value)) def ebind( self, function: Callable[[Literal[None]], MonadType], ) -> MonadType: """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return either a 'Nothing' or 'Some' type object. """ return function(self._inner_value) def value_or(self, default_value: NewValueType) -> NewValueType: """Returns the value if we deal with 'Some' or default if 'Nothing'.""" return default_value def unwrap(self) -> NoReturn: """Raises an exception, since it does not have a value inside.""" raise UnwrapFailedError(self) def failure(self) -> None: """Unwraps inner error value from failed monad.""" return self._inner_value @final class Some(Maybe[ValueType]): """ Represents a calculation which has succeeded and contains the result. Quite similar to ``Success`` type. """ def __init__(self, inner_value: ValueType) -> None: """ 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 fmap( self, function: Callable[[ValueType], NewValueType], ) -> 'Some[NewValueType]': """ Applies function to the inner value. Applies 'function' to the contents of the 'Some' instance and returns a new 'Some' object containing the result. 'function' should accept a single "normal" (non-monad) argument and return a non-monad result. """ return Some(function(self._inner_value)) def bind( self, function: Callable[[ValueType], MonadType], ) -> MonadType: """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-monad) argument and return either a 'Nothing' or 'Some' type object. """ return function(self._inner_value) def efmap(self, function) -> 'Some[ValueType]': """Returns the 'Some' instance that was used to call the method.""" return self def ebind(self, function) -> 'Some[ValueType]': """Returns the 'Some' instance that was used to call the method.""" return self def value_or(self, default_value: NewValueType) -> ValueType: """Returns the value if we deal with 'Some' or default if 'Nothing'.""" return self._inner_value def unwrap(self) -> ValueType: """Returns the unwrapped value from the inside of this monad.""" return self._inner_value def failure(self) -> NoReturn: """Raises an exception, since it does not have an error inside.""" raise UnwrapFailedError(self) PK!'T|returns/maybe.pyi# -*- coding: utf-8 -*- from abc import ABCMeta from typing import Callable, NoReturn, overload from typing_extensions import Literal, final from returns.primitives.monad import Monad, NewValueType, ValueType from returns.primitives.types import MonadType class Maybe(Monad[ValueType], metaclass=ABCMeta): @overload @classmethod def new(cls, inner_value: Literal[None]) -> 'Nothing': # type: ignore ... @overload # noqa: F811 @classmethod def new(cls, inner_value: ValueType) -> 'Some[ValueType]': ... @final class Nothing(Maybe[Literal[None]]): _inner_value: Literal[None] def __init__(self, inner_value: Literal[None] = ...) -> None: ... def fmap(self, function) -> 'Nothing': ... def bind(self, function) -> 'Nothing': ... def efmap( self, function: Callable[[Literal[None]], 'NewValueType'], ) -> 'Some[NewValueType]': ... def ebind( self, function: Callable[[Literal[None]], MonadType], ) -> MonadType: ... def value_or(self, default_value: NewValueType) -> NewValueType: ... def unwrap(self) -> NoReturn: ... def failure(self) -> None: ... @final class Some(Maybe[ValueType]): _inner_value: ValueType def __init__(self, inner_value: ValueType) -> None: ... def fmap( self, function: Callable[[ValueType], NewValueType], ) -> 'Some[NewValueType]': ... def bind( self, function: Callable[[ValueType], MonadType], ) -> MonadType: ... def efmap(self, function) -> 'Some[ValueType]': ... def ebind(self, function) -> 'Some[ValueType]': ... def value_or(self, default_value: NewValueType) -> ValueType: ... def unwrap(self) -> ValueType: ... def failure(self) -> NoReturn: ... PK!uhreturns/primitives/__init__.py# -*- coding: utf-8 -*- PK!+ returns/primitives/exceptions.py# -*- coding: utf-8 -*- from typing import TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from returns.primitives.types import MonadType # noqa: Z435, F401 class UnwrapFailedError(Exception): """Raised when a monad can not be unwrapped into a meaningful value.""" def __init__(self, monad: 'MonadType') -> None: """ Saves halted monad in the inner state. So, this monad can later be unpacked from this exception and used as a regular value. """ super().__init__() self.halted_monad = monad class ImmutableStateError(Exception): """Raised when a monad is forced to be mutated.""" PK!ПH!returns/primitives/exceptions.pyi# -*- coding: utf-8 -*- from returns.primitives.types import MonadType class UnwrapFailedError(Exception): def __init__(self, monad: MonadType) -> None: self.halted_monad = monad class ImmutableStateError(Exception): ... PK! 4returns/primitives/monad.py# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Any, Generic, NoReturn, TypeVar from returns.primitives.exceptions import ImmutableStateError ValueType = TypeVar('ValueType') NewValueType = TypeVar('NewValueType') class _BaseMonad(Generic[ValueType], metaclass=ABCMeta): """Utility class to provide all needed magic methods to the contest.""" __slots__ = ('_inner_value',) _inner_value: Any def __setattr__(self, attr_name, attr_value) -> NoReturn: """Makes inner state of the monads immutable.""" raise ImmutableStateError() def __delattr__(self, attr_name) -> NoReturn: # noqa: Z434 """Makes inner state of the monads immutable.""" raise ImmutableStateError() def __str__(self) -> str: """Converts to string.""" return '{0}: {1}'.format( self.__class__.__qualname__, str(self._inner_value), ) def __eq__(self, other) -> bool: """Used to compare two 'Monad' objects.""" if not isinstance(other, _BaseMonad): return False if type(self) != type(other): return False return self._inner_value == other._inner_value # noqa: Z441 class Monad(_BaseMonad[ValueType]): """ Represents a "context" in which calculations can be executed. You won't create 'Monad' 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 def fmap(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:`~efmap`. """ 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:`~ebind`. """ raise NotImplementedError() @abstractmethod def efmap(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:`~fmap`. """ raise NotImplementedError() @abstractmethod def ebind(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) -> ValueType: # 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() PK!}'ccreturns/primitives/monad.pyi# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from typing import Any, Generic, NoReturn, TypeVar # These type variables are widely used in our source code. ValueType = TypeVar('ValueType') # noqa: Y001 NewValueType = TypeVar('NewValueType') # noqa: Y001 class _BaseMonad(Generic[ValueType], metaclass=ABCMeta): __slots__ = ('_inner_value',) _inner_value: Any def __setattr__(self, attr_name, attr_value) -> NoReturn: ... def __delattr__(self, attr_name) -> NoReturn: # noqa: Z434 ... def __str__(self) -> str: ... def __eq__(self, other) -> bool: ... class Monad(_BaseMonad[ValueType]): @abstractmethod def fmap(self, function): ... @abstractmethod def bind(self, function): ... @abstractmethod def efmap(self, function): ... @abstractmethod def ebind(self, function): ... @abstractmethod def value_or(self, default_value): ... @abstractmethod def unwrap(self) -> ValueType: ... @abstractmethod def failure(self): ... PK![aDzzreturns/primitives/types.py# -*- coding: utf-8 -*- from typing import TYPE_CHECKING, TypeVar, Union if TYPE_CHECKING: # pragma: no cover from returns.either import Either # noqa: Z435, F401 from returns.primitives.monad import Monad # noqa: Z435, F401 # We need to have this ugly type because there is no other way around it: MonadType = TypeVar('MonadType', bound=Union['Monad', 'Either']) PK!returns/py.typedPK!R00returns-0.3.1.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.3.1.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!Hc2 returns-0.3.1.dist-info/METADATAWrF_O1[B>;Y_s6?66$ R#H>ɽϽu$ 79QM+0<䆻Ai!;\ZLU־w?zw:1ZXB,=&׬be~9JC1- `vdؐDx DՖVG#P^km )tkM͎St%OSF*Ł)^+}xюƝD@C93+`'- Tq̯޲s%<0M!} m]qG@&0RNGȤY,ӝЁHʻq=6\nSqk7D C攇4gnRO/1B|22}`zY\Ç:s?X:hEԦmǿoyy=Oݨ748ozhvOGh`u&wǓsZ;{ſ/!\_ ï0hޗ[8HN?zuO?{^uG~ap: ]" O x:lse?IŗB^M8 BU^`'PTK]v#-G )s4L ?ܞtʬ(5qYЦmq҄Y6?Z "!*[E9YW6(=m'mU2H6\lrvۭSUll~gq}cwzzö8.5%Z8E]uFXAi-Ms-RКaj8^SsTc0`QmNhOc>"x'W㚭 v~25ǹѣUAa76bd]qd"cڴh+t̹yiqs<[1 Y S\\J~:MmXp)E6: G2" ✮MDWk JZR> cFDg>M(J<יS=ߠ V͋WG::Z ƈX˴nUHp$3㍗<x71m*t%+ųZ}c64rnkZz;3-C]{m iꐫ'E~MRlCBcUYn/,b'M̄*ڸܑ>2""{D_p,7cbs+ޓTi#@s-d1PK!H1kreturns-0.3.1.dist-info/RECORDǒH} T@ 61#T]ɛ>~gFRsv[r8K5Ŵ͹S)xH$Zxm30G7>h`-E99jPFkCInAXփvp%d]iV)zpـݳu,)/b"nkg\Yҿ*Is| > HS˫G-ʼnCCHO) x\#ȸA1>>qc %' uk.ݽ\0aa*j%cT~tRP¿ĞkfftTvf!/hDIi0Q½s9 V@4ۭ Qԗas5lӞdWTmZd,YKC%Wl"3\7 _2ȆZKD2`5Ch{$FFag*vl/K094_t"û2"=H.c\(kPvIurJ ^4j>L> >?8Ď%LdIEn hCϏF7-knEfYFocSAT pvȈv@þuuzߏjl{W8= Nǡ~鰥h[S-c,:; ImA =<6wlւ2{lEM/Y ǿPK!uhreturns/__init__.pyPK!aMIreturns/do_notation.pyPK!dareturns/do_notation.pyiPK!,]returns/either.pyPK!o"aareturns/either.pyiPK!''#returns/functions.pyPK!U__n'returns/functions.pyiPK!^)returns/maybe.pyPK!'T|=returns/maybe.pyiPK!uhEreturns/primitives/__init__.pyPK!+ Ereturns/primitives/exceptions.pyPK!ПH!Hreturns/primitives/exceptions.pyiPK! 4Ireturns/primitives/monad.pyPK!}'cc*Yreturns/primitives/monad.pyiPK![aDzz]returns/primitives/types.pyPK!z_returns/py.typedPK!R00_returns-0.3.1.dist-info/LICENSEPK!HڽTUdreturns-0.3.1.dist-info/WHEELPK!Hc2 dreturns-0.3.1.dist-info/METADATAPK!H1kkreturns-0.3.1.dist-info/RECORDPKOo