1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
|
from abc import ABC
from collections.abc import Callable, Generator, Iterator
from functools import wraps
from inspect import FrameInfo
from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, final, overload
from typing_extensions import Never, ParamSpec
from returns.interfaces.specific import result
from returns.primitives.container import BaseContainer, container_equality
from returns.primitives.exceptions import UnwrapFailedError
from returns.primitives.hkt import Kind2, SupportsKind2
# Definitions:
_ValueType_co = TypeVar('_ValueType_co', covariant=True)
_NewValueType = TypeVar('_NewValueType')
_ErrorType_co = TypeVar('_ErrorType_co', covariant=True)
_NewErrorType = TypeVar('_NewErrorType')
_FirstType = TypeVar('_FirstType')
_FuncParams = ParamSpec('_FuncParams')
class Result( # type: ignore[type-var]
BaseContainer,
SupportsKind2['Result', _ValueType_co, _ErrorType_co],
result.ResultBased2[_ValueType_co, _ErrorType_co],
ABC,
):
"""
Base class for :class:`~Failure` and :class:`~Success`.
:class:`~Result` does not have a public constructor.
Use :func:`~Success` and :func:`~Failure` to construct the needed values.
See also:
- https://bit.ly/361qQhi
- https://hackernoon.com/the-throw-keyword-was-a-mistake-l9e532di
"""
__slots__ = ('_trace',)
__match_args__ = ('_inner_value',)
_inner_value: _ValueType_co | _ErrorType_co
_trace: list[FrameInfo] | None
#: Typesafe equality comparison with other `Result` objects.
equals = container_equality
@property
def trace(self) -> list[FrameInfo] | None:
"""Returns a list with stack trace when :func:`~Failure` was called."""
return self._trace
def swap(self) -> 'Result[_ErrorType_co, _ValueType_co]':
"""
Swaps value and error types.
So, values become errors and errors become values.
It is useful when you have to work with errors a lot.
And since we have a lot of ``.bind_`` related methods
and only a single ``.lash`` - it is easier to work with values.
.. code:: python
>>> from returns.result import Success, Failure
>>> assert Success(1).swap() == Failure(1)
>>> assert Failure(1).swap() == Success(1)
"""
def map(
self,
function: Callable[[_ValueType_co], _NewValueType],
) -> 'Result[_NewValueType, _ErrorType_co]':
"""
Composes successful container with a pure function.
.. code:: python
>>> from returns.result import Failure, Success
>>> def mappable(string: str) -> str:
... return string + 'b'
>>> assert Success('a').map(mappable) == Success('ab')
>>> assert Failure('a').map(mappable) == Failure('a')
"""
def apply(
self,
container: Kind2[
'Result',
Callable[[_ValueType_co], _NewValueType],
_ErrorType_co,
],
) -> 'Result[_NewValueType, _ErrorType_co]':
"""
Calls a wrapped function in a container on this container.
.. code:: python
>>> from returns.result import Failure, Success
>>> def appliable(string: str) -> str:
... return string + 'b'
>>> assert Success('a').apply(Success(appliable)) == Success('ab')
>>> assert Failure('a').apply(Success(appliable)) == Failure('a')
>>> assert Success('a').apply(Failure(1)) == Failure(1)
>>> assert Failure(1).apply(Failure(2)) == Failure(1)
"""
def bind(
self,
function: Callable[
[_ValueType_co],
Kind2['Result', _NewValueType, _ErrorType_co],
],
) -> 'Result[_NewValueType, _ErrorType_co]':
"""
Composes successful container with a function that returns a container.
.. code:: python
>>> from returns.result import Result, Success, Failure
>>> def bindable(arg: str) -> Result[str, str]:
... if len(arg) > 1:
... return Success(arg + 'b')
... return Failure(arg + 'c')
>>> assert Success('aa').bind(bindable) == Success('aab')
>>> assert Success('a').bind(bindable) == Failure('ac')
>>> assert Failure('a').bind(bindable) == Failure('a')
"""
#: Alias for `bind_result` method, it is the same as `bind` here.
bind_result = bind
def alt(
self,
function: Callable[[_ErrorType_co], _NewErrorType],
) -> 'Result[_ValueType_co, _NewErrorType]':
"""
Composes failed container with a pure function to modify failure.
.. code:: python
>>> from returns.result import Failure, Success
>>> def altable(arg: str) -> str:
... return arg + 'b'
>>> assert Success('a').alt(altable) == Success('a')
>>> assert Failure('a').alt(altable) == Failure('ab')
"""
def lash(
self,
function: Callable[
[_ErrorType_co],
Kind2['Result', _ValueType_co, _NewErrorType],
],
) -> 'Result[_ValueType_co, _NewErrorType]':
"""
Composes failed container with a function that returns a container.
.. code:: python
>>> from returns.result import Result, Success, Failure
>>> def lashable(arg: str) -> Result[str, str]:
... if len(arg) > 1:
... return Success(arg + 'b')
... return Failure(arg + 'c')
>>> assert Success('a').lash(lashable) == Success('a')
>>> assert Failure('a').lash(lashable) == Failure('ac')
>>> assert Failure('aa').lash(lashable) == Success('aab')
"""
def __iter__(self) -> Iterator[_ValueType_co]:
"""API for :ref:`do-notation`."""
yield self.unwrap()
@classmethod
def do(
cls,
expr: Generator[_NewValueType, None, None],
) -> 'Result[_NewValueType, _NewErrorType]':
"""
Allows working with unwrapped values of containers in a safe way.
.. code:: python
>>> from returns.result import Result, Failure, Success
>>> assert Result.do(
... first + second
... for first in Success(2)
... for second in Success(3)
... ) == Success(5)
>>> assert Result.do(
... first + second
... for first in Failure('a')
... for second in Success(3)
... ) == Failure('a')
See :ref:`do-notation` to learn more.
This feature requires our :ref:`mypy plugin <mypy-plugins>`.
"""
try:
return Result.from_value(next(expr))
except UnwrapFailedError as exc:
return exc.halted_container # type: ignore
def value_or(
self,
default_value: _NewValueType,
) -> _ValueType_co | _NewValueType:
"""
Get value or default value.
.. code:: python
>>> from returns.result import Failure, Success
>>> assert Success(1).value_or(2) == 1
>>> assert Failure(1).value_or(2) == 2
"""
def unwrap(self) -> _ValueType_co:
"""
Get value or raise exception.
.. code:: pycon
:force:
>>> from returns.result import Failure, Success
>>> assert Success(1).unwrap() == 1
>>> Failure(1).unwrap()
Traceback (most recent call last):
...
returns.primitives.exceptions.UnwrapFailedError
"""
def failure(self) -> _ErrorType_co:
"""
Get failed value or raise exception.
.. code:: pycon
:force:
>>> from returns.result import Failure, Success
>>> assert Failure(1).failure() == 1
>>> Success(1).failure()
Traceback (most recent call last):
...
returns.primitives.exceptions.UnwrapFailedError
"""
@classmethod
def from_value(
cls,
inner_value: _NewValueType,
) -> 'Result[_NewValueType, Any]':
"""
One more value to create success unit values.
It is useful as a united way to create a new value from any container.
.. code:: python
>>> from returns.result import Result, Success
>>> assert Result.from_value(1) == Success(1)
You can use this method or :func:`~Success`,
choose the most convenient for you.
"""
return Success(inner_value)
@classmethod
def from_failure(
cls,
inner_value: _NewErrorType,
) -> 'Result[Any, _NewErrorType]':
"""
One more value to create failure unit values.
It is useful as a united way to create a new value from any container.
.. code:: python
>>> from returns.result import Result, Failure
>>> assert Result.from_failure(1) == Failure(1)
You can use this method or :func:`~Failure`,
choose the most convenient for you.
"""
return Failure(inner_value)
@classmethod
def from_result(
cls,
inner_value: 'Result[_NewValueType, _NewErrorType]',
) -> 'Result[_NewValueType, _NewErrorType]':
"""
Creates a new ``Result`` instance from existing ``Result`` instance.
.. code:: python
>>> from returns.result import Result, Failure, Success
>>> assert Result.from_result(Success(1)) == Success(1)
>>> assert Result.from_result(Failure(1)) == Failure(1)
This is a part of
:class:`returns.interfaces.specific.result.ResultBasedN` interface.
"""
return inner_value
@final # noqa: WPS338
class Failure(Result[Any, _ErrorType_co]): # noqa: WPS338
"""
Represents a calculation which has failed.
It should contain an error code or message.
"""
__slots__ = ()
_inner_value: _ErrorType_co
def __init__(self, inner_value: _ErrorType_co) -> None:
"""Failure constructor."""
super().__init__(inner_value)
object.__setattr__(self, '_trace', self._get_trace())
if not TYPE_CHECKING: # noqa: WPS604 # pragma: no branch
def alt(self, function):
"""Composes failed container with a pure function to modify failure.""" # noqa: E501
return Failure(function(self._inner_value))
def map(self, function):
"""Does nothing for ``Failure``."""
return self
def bind(self, function):
"""Does nothing for ``Failure``."""
return self
#: Alias for `bind` method. Part of the `ResultBasedN` interface.
bind_result = bind
def lash(self, function):
"""Composes this container with a function returning container."""
return function(self._inner_value)
def apply(self, container):
"""Does nothing for ``Failure``."""
return self
def value_or(self, default_value):
"""Returns default value for failed container."""
return default_value
def swap(self):
"""Failures swap to :class:`Success`."""
return Success(self._inner_value)
def unwrap(self) -> Never:
"""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) -> _ErrorType_co:
"""Returns failed value."""
return self._inner_value
def _get_trace(self) -> list[FrameInfo] | None:
"""Method that will be monkey patched when trace is active."""
@final
class Success(Result[_ValueType_co, Any]):
"""
Represents a calculation which has succeeded and contains the result.
Contains the computation value.
"""
__slots__ = ()
_inner_value: _ValueType_co
def __init__(self, inner_value: _ValueType_co) -> None:
"""Success constructor."""
super().__init__(inner_value)
if not TYPE_CHECKING: # noqa: WPS604 # pragma: no branch
def alt(self, function):
"""Does nothing for ``Success``."""
return self
def map(self, function):
"""Composes current container with a pure function."""
return Success(function(self._inner_value))
def bind(self, function):
"""Binds current container to a function that returns container."""
return function(self._inner_value)
#: Alias for `bind` method. Part of the `ResultBasedN` interface.
bind_result = bind
def lash(self, function):
"""Does nothing for ``Success``."""
return self
def apply(self, container):
"""Calls a wrapped function in a container on this container."""
if isinstance(container, Success):
return self.map(container.unwrap())
return container
def value_or(self, default_value):
"""Returns the value for successful container."""
return self._inner_value
def swap(self):
"""Successes swap to :class:`Failure`."""
return Failure(self._inner_value)
def unwrap(self) -> _ValueType_co:
"""Returns the unwrapped value from successful container."""
return self._inner_value
def failure(self) -> Never:
"""Raises an exception for successful container."""
raise UnwrapFailedError(self)
# Aliases:
#: Alias for ``Result[_ValueType_co, Exception]``.
ResultE: TypeAlias = Result[_ValueType_co, Exception]
# Decorators:
_ExceptionType = TypeVar('_ExceptionType', bound=Exception)
@overload
def safe(
function: Callable[_FuncParams, _ValueType_co],
/,
) -> Callable[_FuncParams, ResultE[_ValueType_co]]: ...
@overload
def safe(
exceptions: tuple[type[_ExceptionType], ...],
) -> Callable[
[Callable[_FuncParams, _ValueType_co]],
Callable[_FuncParams, Result[_ValueType_co, _ExceptionType]],
]: ...
def safe( # noqa: WPS234
exceptions: (
Callable[_FuncParams, _ValueType_co] | tuple[type[_ExceptionType], ...]
),
) -> (
Callable[_FuncParams, ResultE[_ValueType_co]]
| Callable[
[Callable[_FuncParams, _ValueType_co]],
Callable[_FuncParams, Result[_ValueType_co, _ExceptionType]],
]
):
"""
Decorator to convert exception-throwing function to ``Result`` container.
Should be used with care, since it only catches ``Exception`` subclasses.
It does not catch ``BaseException`` subclasses.
If you need to mark ``async`` function as ``safe``,
use :func:`returns.future.future_safe` instead.
This decorator only works with sync functions. Example:
.. code:: python
>>> from returns.result import Failure, Success, safe
>>> @safe
... def might_raise(arg: int) -> float:
... return 1 / arg
>>> assert might_raise(1) == Success(1.0)
>>> assert isinstance(might_raise(0), Failure)
You can also use it with explicit exception types as the first argument:
.. code:: python
>>> from returns.result import Failure, Success, safe
>>> @safe(exceptions=(ZeroDivisionError,))
... def might_raise(arg: int) -> float:
... return 1 / arg
>>> assert might_raise(1) == Success(1.0)
>>> assert isinstance(might_raise(0), Failure)
In this case, only exceptions that are explicitly
listed are going to be caught.
Similar to :func:`returns.io.impure_safe`
and :func:`returns.future.future_safe` decorators.
"""
def factory(
inner_function: Callable[_FuncParams, _ValueType_co],
inner_exceptions: tuple[type[_ExceptionType], ...],
) -> Callable[_FuncParams, Result[_ValueType_co, _ExceptionType]]:
@wraps(inner_function)
def decorator(
*args: _FuncParams.args,
**kwargs: _FuncParams.kwargs,
) -> Result[_ValueType_co, _ExceptionType]:
try:
return Success(inner_function(*args, **kwargs))
except inner_exceptions as exc:
return Failure(exc)
return decorator
if isinstance(exceptions, tuple):
return lambda function: factory(function, exceptions)
return factory(
exceptions,
(Exception,), # type: ignore[arg-type]
)
def attempt(
func: Callable[[_FirstType], _NewValueType],
) -> Callable[[_FirstType], Result[_NewValueType, _FirstType]]:
"""
Decorator to convert exception-throwing function to ``Result`` container.
It's very similar with :func:`returns.result.safe`, the difference is when
an exception is raised it won't wrap that given exception into a Failure,
it'll wrap the argument that lead to the exception.
.. code:: python
>>> import json
>>> from typing import Dict, Any
>>> from returns.result import Failure, Success, attempt
>>> @attempt
... def parse_json(string: str) -> Dict[str, Any]:
... return json.loads(string)
>>> assert parse_json('{"key": "value"}') == Success({'key': 'value'})
>>> assert parse_json('incorrect input') == Failure('incorrect input')
"""
@wraps(func)
def decorator(arg: _FirstType) -> Result[_NewValueType, _FirstType]:
try:
return Success(func(arg))
except Exception:
return Failure(arg)
return decorator
|