PK!\Treturns/__init__.py# -*- coding: utf-8 -*- """ We define public API here. So, later our code can be used like so: .. code:: python import returns result: returns.Result[int, str] See: https://github.com/dry-python/returns/issues/73 """ from returns.converters import maybe_to_result, result_to_maybe from returns.functions import compose, raise_exception from returns.io import IO, impure from returns.maybe import Maybe, Nothing, Some, maybe from returns.pipeline import is_successful, pipeline from returns.primitives.exceptions import UnwrapFailedError from returns.result import Failure, Result, Success, safe __all__ = ( # Functions: 'compose', 'raise_exception', # IO: 'IO', 'impure', # Maybe: 'Some', 'Nothing', 'Maybe', 'maybe', # Result: 'safe', 'Failure', 'Result', 'Success', 'UnwrapFailedError', # pipeline: 'is_successful', 'pipeline', # Converters: 'result_to_maybe', 'maybe_to_result', ) PK!uhreturns/contrib/__init__.py# -*- coding: utf-8 -*- PK!uh returns/contrib/mypy/__init__.py# -*- coding: utf-8 -*- PK!uF (returns/contrib/mypy/decorator_plugin.py# -*- coding: utf-8 -*- """ Custom mypy plugin to solve the temporary problem with untyped decorators. This problem appears when we try to change the return type of the function. However, currently it is impossible due to this bug: https://github.com/python/mypy/issues/3157 This plugin is a temporary solution to the problem. It should be later replaced with the official way of doing things. ``mypy`` API docs are here: https://mypy.readthedocs.io/en/latest/extending_mypy.html We use ``pytest-mypy-plugins`` to test that it works correctly, see: https://github.com/mkurnikov/pytest-mypy-plugins """ from typing import Callable, Optional, Type from mypy.plugin import FunctionContext, Plugin from mypy.types import CallableType #: Set of full names of our decorators. _TYPED_DECORATORS = { 'returns.result.safe', 'returns.io.impure', 'returns.maybe.maybe', } def _change_decorator_function_type( decorator: CallableType, arg_type: CallableType, ) -> CallableType: """Replaces revealed argument types by mypy with types from decorated.""" return decorator.copy_modified( arg_types=arg_type.arg_types, arg_kinds=arg_type.arg_kinds, arg_names=arg_type.arg_names, variables=arg_type.variables, is_ellipsis_args=arg_type.is_ellipsis_args, ) def _analyze_decorator(function_ctx: FunctionContext): """Tells us what to do when one of the typed decorators is called.""" if not isinstance(function_ctx.arg_types[0][0], CallableType): return function_ctx.default_return_type if not isinstance(function_ctx.default_return_type, CallableType): return function_ctx.default_return_type return _change_decorator_function_type( function_ctx.default_return_type, function_ctx.arg_types[0][0], ) class _TypedDecoratorPlugin(Plugin): def get_function_hook( # type: ignore self, fullname: str, ) -> Optional[Callable[[FunctionContext], Type]]: """ One of the specified ``mypy`` callbacks. Runs on each function call in the source code. We are only interested in a particular subset of all functions. So, we return a function handler for them. Otherwise, we return ``None``. """ if fullname in _TYPED_DECORATORS: return _analyze_decorator return None def plugin(version: str) -> Type[Plugin]: """Plugin's public API and entrypoint.""" return _TypedDecoratorPlugin PK!wYreturns/converters.py# -*- coding: utf-8 -*- from typing import TypeVar, overload from returns.io import IO from returns.maybe import Maybe from returns.result import Failure, Result, Success _ValueType = TypeVar('_ValueType') _ErrorType = TypeVar('_ErrorType') def result_to_maybe( result_container: Result[_ValueType, _ErrorType], ) -> Maybe[_ValueType]: """Converts ``Result`` container to ``Maybe`` container.""" return Maybe.new(result_container.value_or(None)) def maybe_to_result( maybe_container: Maybe[_ValueType], ) -> Result[_ValueType, None]: """Converts ``Maybe`` container to ``Result`` container.""" inner_value = maybe_container.value_or(None) if inner_value is not None: return Success(inner_value) return Failure(inner_value) @overload def join(container: IO[IO[_ValueType]]) -> IO[_ValueType]: """Case for ``IO`` container.""" @overload def join(container: Maybe[Maybe[_ValueType]]) -> Maybe[_ValueType]: """Case for ``Maybe`` container.""" @overload def join( container: Result[Result[_ValueType, _ErrorType], _ErrorType], ) -> Result[_ValueType, _ErrorType]: """Case for ``Result`` container.""" def join(container): """Joins two nested containers together.""" return container._inner_value # noqa: Z441 PK!hN6++returns/functions.py# -*- coding: utf-8 -*- from typing import Callable, NoReturn, TypeVar # Just aliases: _FirstType = TypeVar('_FirstType') _SecondType = TypeVar('_SecondType') _ThirdType = TypeVar('_ThirdType') def compose( first: Callable[[_FirstType], _SecondType], second: Callable[[_SecondType], _ThirdType], ) -> Callable[[_FirstType], _ThirdType]: """ Allows function composition. Works as: ``second . first`` You can read it as "second after first". .. code:: python from returns.functions import compose logged_int = compose(int, print)('123') # => returns: 123 # => prints: 123 We can only compose functions with one argument and one return. Type checked. """ return lambda argument: second(first(argument)) def raise_exception(exception: Exception) -> NoReturn: """ Helper function to raise exceptions as a function. It might be required as a compatibility tool for existing APIs. That's how it can be used: .. code:: python from returns.functions import raise_exception # Some operation result: user: Failure[UserDoesNotExistError] # Here we unwrap internal exception and raise it: user.fix(raise_exception) See: https://github.com/dry-python/returns/issues/56 """ raise exception PK!^.] ] returns/io.py# -*- coding: utf-8 -*- from functools import wraps from inspect import iscoroutinefunction from typing import Callable, Coroutine, Generic, TypeVar, overload from typing_extensions import final from returns.primitives.container import BaseContainer _ValueType = TypeVar('_ValueType') _NewValueType = TypeVar('_NewValueType') # Helpers: _FirstType = TypeVar('_FirstType') _SecondType = TypeVar('_SecondType') @final class IO(Generic[_ValueType], BaseContainer): """ Explicit marker for impure function results. We call it "marker" since once it is marked, it cannot be unmarked. ``IO`` is also a container. But, it is different in a way that it cannot be unwrapped / rescued / fixed. There's no way to directly get its internal value. """ _inner_value: _ValueType def __init__(self, inner_value: _ValueType) -> None: """Required for typing.""" BaseContainer.__init__(self, inner_value) # type: ignore # noqa: Z462 def map( # noqa: A003 self, function: Callable[[_ValueType], _NewValueType], ) -> 'IO[_NewValueType]': """ Applies function to the inner value. Applies 'function' to the contents of the IO instance and returns a new IO object containing the result. 'function' should accept a single "normal" (non-container) argument and return a non-container result. """ return IO(function(self._inner_value)) def bind( self, function: Callable[[_ValueType], 'IO[_NewValueType]'], ) -> 'IO[_NewValueType]': """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-container) argument and return IO type object. """ return function(self._inner_value) @overload def impure( # type: ignore function: Callable[..., Coroutine[_FirstType, _SecondType, _NewValueType]], ) -> Callable[ ..., Coroutine[_FirstType, _SecondType, IO[_NewValueType]], ]: """Case for async functions.""" @overload def impure( function: Callable[..., _NewValueType], ) -> Callable[..., IO[_NewValueType]]: """Case for regular functions.""" def impure(function): """ Decorator to mark function that it returns :py:class:`IO` container. Supports both async and regular functions. """ if iscoroutinefunction(function): async def decorator(*args, **kwargs): return IO(await function(*args, **kwargs)) else: def decorator(*args, **kwargs): return IO(function(*args, **kwargs)) return wraps(function)(decorator) PK!!Cooreturns/maybe.py# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from functools import wraps from inspect import iscoroutinefunction from typing import ( Any, Callable, Coroutine, Generic, Optional, TypeVar, Union, overload, ) from typing_extensions import final from returns.primitives.container import BaseContainer from returns.primitives.exceptions import UnwrapFailedError # Aliases: _ValueType = TypeVar('_ValueType') _NewValueType = TypeVar('_NewValueType') _ErrorType = TypeVar('_ErrorType') class Maybe( Generic[_ValueType], BaseContainer, metaclass=ABCMeta, ): """ Represents a result of a series of commutation that can return ``None``. An alternative to using exceptions or constant ``is None`` checks. ``Maybe`` is an abstract type and should not be instantiated directly. Instead use ``Some`` and ``Nothing``. """ _inner_value: Optional[_ValueType] @classmethod def new(cls, inner_value: Optional[_ValueType]) -> 'Maybe[_ValueType]': """Creates new instance of Maybe container based on a value.""" if inner_value is None: return _Nothing(inner_value) return _Some(inner_value) @abstractmethod # noqa: A003 def map( self, function: Callable[[_ValueType], Optional[_NewValueType]], ) -> 'Maybe[_NewValueType]': # pragma: no cover """Abstract method to compose container with a pure function.""" raise NotImplementedError() @abstractmethod def bind( self, function: Callable[[_ValueType], 'Maybe[_NewValueType]'], ) -> 'Maybe[_NewValueType]': # pragma: no cover """Abstract method to compose container with other container.""" raise NotImplementedError() @abstractmethod def fix( self, function: Union[ # We use this union to make a good balance # between correct and useful typing: Callable[[None], Optional[_NewValueType]], # correct Callable[[], Optional[_NewValueType]], # useful ], ) -> 'Maybe[_NewValueType]': # pragma: no cover """Abstract method to compose container with a pure function.""" raise NotImplementedError() @abstractmethod def rescue( self, function: Union[ # We use this union to make a good balance # between correct and useful typing: Callable[[None], 'Maybe[_NewValueType]'], # correct Callable[[], 'Maybe[_NewValueType]'], # useful ], ) -> 'Maybe[_NewValueType]': # pragma: no cover """Abstract method to compose container with other container.""" # TODO: allow Callable[[None], 'Maybe[_NewValueType]'] raise NotImplementedError() @abstractmethod def value_or( self, default_value: _NewValueType, ) -> Union[_ValueType, _NewValueType]: # pragma: no cover """Get value or default value.""" raise NotImplementedError() @abstractmethod def unwrap(self) -> _ValueType: # pragma: no cover """Get value or raise exception.""" raise NotImplementedError() @final # noqa: Z214 class _Nothing(Maybe[Any]): """Represents an empty state.""" _inner_value: None def __init__(self, inner_value: None = None) -> None: # noqa: Z459 """ Wraps the given value in the Container. 'value' can only be ``None``. """ BaseContainer.__init__(self, inner_value) # type: ignore # noqa: Z462 def __str__(self): """Custom str definition without state inside.""" return '' def map(self, function): # noqa: A003 """Returns the 'Nothing' instance that was used to call the method.""" return self def bind(self, function): """Returns the 'Nothing' 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 'Some' instance and returns a new 'Some' object containing the result. 'function' should not accept any arguments and return a non-container result. """ try: return Maybe.new(function()) except TypeError: return Maybe.new(function(self._inner_value)) def rescue(self, function): """ Applies 'function' to the result of a previous calculation. 'function' should not accept any arguments and return Maybe a 'Nothing' or 'Some' type object. """ try: return function() except TypeError: return function(self._inner_value) def value_or(self, default_value): """Returns the value if we deal with 'Some' or default if 'Nothing'.""" return default_value def unwrap(self): """Raises an exception, since it does not have a value inside.""" raise UnwrapFailedError(self) @final class _Some(Maybe[_ValueType]): """ Represents a calculation which has succeeded and contains the value. Quite similar to ``Success`` type. """ _inner_value: _ValueType def __init__(self, inner_value: _ValueType) -> None: """Required for typing.""" BaseContainer.__init__(self, inner_value) # type: ignore # noqa: Z462 def map(self, function): # noqa: A003 """ Applies function to the inner value. Applies 'function' to the contents of the 'Some' instance and returns a new 'Maybe' object containing the result. 'function' should accept a single "normal" (non-container) argument and return a non-container result. """ return Maybe.new(function(self._inner_value)) def bind(self, function): """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-container) argument and return 'Nothing' or 'Some' type object. """ return function(self._inner_value) def fix(self, function): """Returns the 'Some' instance that was used to call the method.""" return self def rescue(self, function): """Returns the 'Some' instance that was used to call the method.""" return self def value_or(self, default_value): """Returns the value if we deal with 'Some' or default if 'Nothing'.""" return self._inner_value def unwrap(self): """Returns the unwrapped value from the inside of this container.""" return self._inner_value def Some(inner_value: Optional[_ValueType]) -> Maybe[_ValueType]: # noqa: N802 """Public unit function of protected `_Some` type.""" return Maybe.new(inner_value) #: Public unit value of protected `_Nothing` type. Nothing: Maybe[Any] = _Nothing() @overload # noqa: Z320 def maybe( # type: ignore function: Callable[ ..., Coroutine[_ValueType, _ErrorType, Optional[_NewValueType]], ], ) -> Callable[ ..., Coroutine[_ValueType, _ErrorType, Maybe[_NewValueType]], ]: """Case for async functions.""" @overload def maybe( function: Callable[..., Optional[_NewValueType]], ) -> Callable[..., Maybe[_NewValueType]]: """Case for regular functions.""" def maybe(function): """ Decorator to covert ``None`` returning function to ``Maybe`` container. Supports both async and regular functions. """ if iscoroutinefunction(function): async def decorator(*args, **kwargs): regular_result = await function(*args, **kwargs) if regular_result is None: return Nothing return Some(regular_result) else: def decorator(*args, **kwargs): regular_result = function(*args, **kwargs) if regular_result is None: return Nothing return Some(regular_result) return wraps(function)(decorator) PK!;l#returns/pipeline.py# -*- coding: utf-8 -*- from functools import wraps from inspect import iscoroutinefunction from typing import Callable, Coroutine, TypeVar, Union, overload from returns.maybe import Maybe from returns.primitives.exceptions import UnwrapFailedError from returns.result import Result # Logical aliases: _Unwrapable = Union[Result, Maybe] # Just aliases: _FirstType = TypeVar('_FirstType') _SecondType = TypeVar('_SecondType') # Hacks for functions: _ReturnsResultType = TypeVar( '_ReturnsResultType', bound=Callable[..., _Unwrapable], ) _AsyncReturnsResultType = TypeVar( '_AsyncReturnsResultType', bound=Callable[..., Coroutine[_FirstType, _SecondType, _Unwrapable]], ) def is_successful(container: _Unwrapable) -> bool: """ 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 @overload def pipeline( function: _AsyncReturnsResultType, ) -> _AsyncReturnsResultType: """Case for async functions.""" @overload def pipeline(function: _ReturnsResultType) -> _ReturnsResultType: """Case for regular functions.""" def pipeline(function): # noqa: C901 """ Decorator to enable 'do-notation' context. Should be used for series of computations that rely on ``.unwrap`` method. Supports both async and regular functions. """ if iscoroutinefunction(function): async def decorator(*args, **kwargs): try: return await function(*args, **kwargs) except UnwrapFailedError as exc: return exc.halted_container else: def decorator(*args, **kwargs): try: return function(*args, **kwargs) except UnwrapFailedError as exc: return exc.halted_container return wraps(function)(decorator) PK!uhreturns/primitives/__init__.py# -*- coding: utf-8 -*- PK!o@%%returns/primitives/container.py# -*- coding: utf-8 -*- from abc import ABCMeta from typing import Any, Callable, NoReturn, TypeVar, Union from typing_extensions import Protocol, runtime from returns.primitives.exceptions import ImmutableStateError _ValueType = TypeVar('_ValueType', covariant=True) _NewValueType = TypeVar('_NewValueType') _ErrorType = TypeVar('_ErrorType', covariant=True) _NewErrorType = TypeVar('_NewErrorType') class BaseContainer(object, metaclass=ABCMeta): """Utility class to provide all needed magic methods to the context.""" __slots__ = ('_inner_value',) _inner_value: Any 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) # noqa: Z462 def __setattr__(self, attr_name: str, attr_value) -> NoReturn: """Makes inner state of the containers immutable.""" raise ImmutableStateError() def __delattr__(self, attr_name: str) -> NoReturn: # noqa: Z434 """Makes inner state of the containers immutable.""" raise ImmutableStateError() def __str__(self) -> str: """Converts to string.""" return '<{0}: {1}>'.format( self.__class__.__qualname__.strip('_'), str(self._inner_value), ) def __eq__(self, other) -> bool: """Used to compare two 'Container' objects.""" if type(self) != type(other): return False return self._inner_value == other._inner_value # noqa: Z441 @runtime class Bindable(Protocol[_ValueType]): """ Represents a "context" in which calculations can be executed. ``Bindable`` allows you to bind together a series of calculations while maintaining the context of that specific container. """ def bind( self, function: Callable[[_ValueType], 'Bindable[_NewValueType]'], ) -> 'Bindable[_NewValueType]': """ Applies 'function' to the result of a previous calculation. And returns a new container. Works for containers that represent success. Is the opposite of :meth:`Rescueable.rescue`. """ @runtime class Mappable(Protocol[_ValueType]): """ Allows to chain wrapped values with regular functions. Behaves like functor. """ def map( # noqa: A003 self, function: Callable[[_ValueType], _NewValueType], ) -> 'Mappable[_NewValueType]': """ Applies 'function' to the contents of the functor. And returns a new functor value. Is the opposite of :meth:`Fixable.fix`. """ @runtime class Fixable(Protocol[_ValueType, _ErrorType]): """Represents containers that can be fixed and rescued.""" def fix( self, function: Callable[[_ErrorType], _NewValueType], ) -> 'Fixable[_NewValueType, _ErrorType]': """ Applies 'function' to the error and transforms failure to success. And returns a new functor value. Works for containers that represent failure. Is the opposite of :meth:`Mappable.map`. """ @runtime class Rescueable(Protocol[_ValueType, _ErrorType]): """ Represents a "context" in which calculations can be executed. ``Rescueable`` allows you to bind together a series of calculations while maintaining the context of that specific container. """ def rescue( self, function: Callable[ [_ErrorType], 'Rescueable[_NewValueType, _NewErrorType]', ], ) -> 'Rescueable[_NewValueType, _NewErrorType]': """ Applies 'function' to the result of a previous calculation. And returns a new container. Works for containers that represent failure. Is the opposite of :meth:`~bind`. """ @runtime class Unwrapable(Protocol[_ValueType]): """Represents containers that can unwrap and return its wrapped value.""" def value_or( self, default_value: _NewValueType, ) -> Union[_ValueType, _NewValueType]: """Forces to unwrap value from container or return a default.""" def unwrap(self) -> _ValueType: """ Custom magic method to unwrap inner value from container. 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`. """ @runtime class UnwrapableFailure(Protocol[_ValueType, _ErrorType]): """Allows to unwrap failures.""" def map_failure( self, function: Callable[[_ErrorType], _NewErrorType], ) -> 'Fixable[_ValueType, _NewErrorType]': """ Uses 'function' to transform one error to another. And returns a new functor value. Works for containers that represent failure. Is the opposite of :meth:`~map`. """ def failure(self) -> _ErrorType: """ Custom magic method to unwrap inner value from the failed container. This method is the opposite of :meth:`~unwrap`. """ PK!P8 returns/primitives/exceptions.py# -*- coding: utf-8 -*- from typing import TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from returns.primitives.container import BaseContainer # noqa: F401, Z435 class UnwrapFailedError(Exception): """Raised when a container can not be unwrapped into a meaningful value.""" def __init__(self, container: 'BaseContainer') -> None: """ 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/py.typedPK!t""returns/result.py# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from functools import wraps from inspect import iscoroutinefunction from typing import Any, Callable, Coroutine, Generic, TypeVar, Union, overload from typing_extensions import final from returns.primitives.container import BaseContainer from returns.primitives.exceptions import UnwrapFailedError # Regular type vars, work correctly: _ValueType = TypeVar('_ValueType') _NewValueType = TypeVar('_NewValueType') _ErrorType = TypeVar('_ErrorType') _NewErrorType = TypeVar('_NewErrorType') class Result( Generic[_ValueType, _ErrorType], BaseContainer, metaclass=ABCMeta, ): """Base class for _Failure and _Success.""" _inner_value: Union[_ValueType, _ErrorType] @abstractmethod # noqa: A003 def map( self, function: Callable[[_ValueType], _NewValueType], ) -> 'Result[_NewValueType, _ErrorType]': # pragma: no cover """Abstract method to compose container with pure function.""" raise NotImplementedError() @abstractmethod def bind( self, function: Callable[ [_ValueType], 'Result[_NewValueType, _NewErrorType]', ], ) -> 'Result[_NewValueType, _NewErrorType]': # pragma: no cover """Abstract method to compose container with other container.""" raise NotImplementedError() @abstractmethod def fix( self, function: Callable[[_ErrorType], _NewValueType], ) -> 'Result[_NewValueType, _ErrorType]': # pragma: no cover """Abstract method to compose container with pure function.""" raise NotImplementedError() @abstractmethod def map_failure( self, function: Callable[[_ErrorType], _NewErrorType], ) -> 'Result[_ValueType, _NewErrorType]': # pragma: no cover """Abstract method to compose container with pure function.""" raise NotImplementedError() @abstractmethod def rescue( self, function: Callable[ [_ErrorType], 'Result[_NewValueType, _NewErrorType]', ], ) -> 'Result[_NewValueType, _NewErrorType]': # pragma: no cover """Abstract method to compose container with other container.""" raise NotImplementedError() @abstractmethod def value_or( self, default_value: _NewValueType, ) -> Union[_ValueType, _NewValueType]: # pragma: no cover """Get value or default value.""" raise NotImplementedError() @abstractmethod def unwrap(self) -> _ValueType: # pragma: no cover """Get value or raise exception.""" raise NotImplementedError() @abstractmethod def failure(self) -> _ErrorType: # pragma: no cover """Get failed value or raise exception.""" raise NotImplementedError() @final # noqa: Z214 class _Failure(Result[Any, _ErrorType]): """ Represents a calculation which has failed. It should contain an error code or message. Should not be used directly. """ _inner_value: _ErrorType def __init__(self, inner_value: _ErrorType) -> None: """Required for typing.""" BaseContainer.__init__(self, inner_value) # type: ignore # noqa: Z462 def map(self, function): # noqa: A003 """Returns the '_Failure' instance that was used to call the method.""" return self def map_failure(self, function): """ Applies function to the error value. Applies 'function' to the contents of the '_Failure' instance and returns a new '_Failure' object containing the result. 'function' should accept a single "normal" (non-container) argument and return a non-container result. """ return _Failure(function(self._inner_value)) 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-container) argument and return a non-container 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-container) 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.""" if isinstance(self._inner_value, Exception): raise UnwrapFailedError(self) from self._inner_value raise UnwrapFailedError(self) def failure(self): """Unwraps inner error value from failed container.""" return self._inner_value @final # noqa: Z214 class _Success(Result[_ValueType, Any]): """ Represents a calculation which has succeeded and contains the result. Contains the computation value. Should not be used directly. """ _inner_value: _ValueType def __init__(self, inner_value: _ValueType) -> None: """Required for typing.""" BaseContainer.__init__(self, inner_value) # type: ignore # noqa: Z462 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-container) argument and return a non-container result. """ return _Success(function(self._inner_value)) def map_failure(self, function): """Returns the '_Success' instance that was used to call the method.""" return self def bind(self, function): """ Applies 'function' to the result of a previous calculation. 'function' should accept a single "normal" (non-container) 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 container.""" return self._inner_value def failure(self): """Raises an exception, since it does not have an error inside.""" raise UnwrapFailedError(self) def Success(inner_value: _ValueType) -> Result[_ValueType, Any]: # noqa: N802 """Public unit function of protected `_Success` type.""" return _Success(inner_value) def Failure(inner_value: _ErrorType) -> Result[Any, _ErrorType]: # noqa: N802 """Public unit function of protected `_Failure` type.""" return _Failure(inner_value) @overload # noqa: Z320 def safe( # type: ignore function: Callable[..., Coroutine[_ValueType, _ErrorType, _NewValueType]], ) -> Callable[ ..., Coroutine[_ValueType, _ErrorType, Result[_NewValueType, Exception]], ]: """Case for async functions.""" @overload def safe( function: Callable[..., _NewValueType], ) -> Callable[..., Result[_NewValueType, Exception]]: """Case for regular functions.""" def safe(function): # noqa: C901 """ Decorator to covert exception throwing function to 'Result' container. Should be used with care, since it only catches 'Exception' subclasses. It does not catch 'BaseException' subclasses. Supports both async and regular functions. """ if iscoroutinefunction(function): async def decorator(*args, **kwargs): try: return Success(await function(*args, **kwargs)) except Exception as exc: return Failure(exc) else: def decorator(*args, **kwargs): try: return Success(function(*args, **kwargs)) except Exception as exc: return Failure(exc) return wraps(function)(decorator) PK!/=returns/unsafe.py# -*- coding: utf-8 -*- from typing import TypeVar from returns.io import IO _ValueType = TypeVar('_ValueType') def unsafe_perform_io(wrapped_in_io: IO[_ValueType]) -> _ValueType: """ Compatibility utility and escape mechanism from ``IO`` world. Just unwraps the internal value from :py:class:`IO ` container. Should be used with caution! Since it might be overused by tired developers. It is recommended to have only one place (module / file) in your program where you allow unsafe operations. We recommend to use ``import-linter`` to enforce this rule: - https://github.com/seddonym/import-linter """ return wrapped_in_io._inner_value # noqa: Z441 PK!q/  returns-0.9.0.dist-info/LICENSECopyright 2016-2019 dry-python organization Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK!HڽTUreturns-0.9.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HA҂j& returns-0.9.0.dist-info/METAD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