repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
toolz | bench/test_memoize_kwargs.py | .py | from toolz import memoize
def test_memoize_kwargs():
@memoize
def f(x, y=3):
return x
for i in range(100000):
f(3)
| 11 | 146 |
toolz | bench/test_curry_baseline.py | .py | from toolz import get
from functools import partial
pairs = [(1, 2) for i in range(100000)]
def test_get():
first = partial(get, 0)
for p in pairs:
first(p)
| 12 | 177 |
toolz | bench/test_get.py | .py | from toolz import get
tuples = [(1, 2, 3) for i in range(100000)]
def test_get():
for tup in tuples:
get(1, tup)
| 9 | 128 |
toolz | bench/test_pluck.py | .py | from toolz import pluck
tuples = [(1, 2, 3) for i in range(100000)]
less_tuples = [(1, 2, 3) for i in range(100)]
def test_pluck():
for i in pluck(2, tuples):
pass
for i in range(1000):
tuple(pluck(2, less_tuples))
| 13 | 243 |
toolz | bench/test_first_iter.py | .py | import itertools
from toolz import first, second
def test_first_iter():
iters = map(iter, [(1, 2) for i in range(1000000)])
for p in iters:
first(p)
def test_second_iter():
iters = map(iter, [(1, 2) for i in range(1000000)])
for p in iters:
second(p)
| 15 | 287 |
toolz | bench/test_first.py | .py | from toolz import first, second
pairs = [(1, 2) for i in range(1000000)]
def test_first():
for p in pairs:
first(p)
def test_second():
for p in pairs:
second(p)
| 14 | 190 |
toolz | bench/test_memoize.py | .py | from toolz import memoize
def test_memoize_no_kwargs():
@memoize
def f(x):
return x
for i in range(100000):
f(3)
| 11 | 144 |
toolz | bench/test_frequencies.py | .py | from toolz import frequencies, identity
big_data = list(range(1000)) * 1000
small_data = list(range(100))
def test_frequencies():
frequencies(big_data)
def test_frequencies_small():
for i in range(1000):
frequencies(small_data)
| 15 | 250 |
toolz | bench/test_sliding_window.py | .py | from toolz import sliding_window
seq = range(1000000)
def test_sliding_window():
list(sliding_window(3, seq))
| 8 | 117 |
toolz | examples/wordcount.py | .py | from toolz import *
def stem(word):
""" Stem word to primitive form """
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"")
wordcount = comp(frequencies, partial(map, stem), str.split)
if __name__ == '__main__':
print(wordcount("This cat jumped over this other cat!"))
# prints {'this': 2, 'cat': 2... | 13 | 358 |
toolz | examples/fib.py | .py | # / 0 if i is 0
# fib(i) = | 1 if i is 1
# \ fib(i - 1) + fib(i - 2) otherwise
def fib(n):
""" Imperative definition of Fibonacci numbers """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# This is intuitive but... | 39 | 857 |
toolz | examples/graph.py | .py | from toolz.curried import *
a, b, c, d, e, f, g = 'abcdefg'
edges = [(a, b), (b, a), (a, c), (a, d), (d, a), (d, e), (e, f), (d, f),
(f, d), (d, g), (e, g)]
out_degrees = countby(first, edges)
# {'a': 3, 'b': 1, 'd': 4, 'e': 2, 'f': 1}
in_degrees = countby(second, edges)
# {'a': 2, 'b': 1, 'c': 1, 'd': 2,... | 32 | 771 |
toolz | tlz/__init__.py | .py | """``tlz`` mirrors the ``toolz`` API and uses ``cytoolz`` if possible.
The ``tlz`` package is installed when ``toolz`` is installed. It provides
a convenient way to use functions from ``cytoolz``--a faster Cython
implementation of ``toolz``--if it is installed, otherwise it uses
functions from ``toolz``.
"""
from . ... | 10 | 338 |
toolz | tlz/_build_tlz.py | .py | import sys
import types
import toolz
from importlib import import_module
from importlib.machinery import ModuleSpec
class TlzLoader:
""" Finds and loads ``tlz`` modules when added to sys.meta_path"""
def __init__(self):
self.always_from_toolz = {
toolz.pipe,
}
def _load_toolz... | 94 | 3,144 |
returns | benchmarks/test_benchmarks.py | .py | """Performance benchmarks for the core ``returns`` containers.
These benchmarks exercise the hot paths of the most commonly used
containers (``Result``, ``Maybe``, ``IO``) together with the pipeline
and iterable helpers. They are measured by CodSpeed in CI.
"""
from returns.io import IO
from returns.iterables import ... | 156 | 4,272 |
returns | docs/conf.py | .py | # Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or mo... | 129 | 3,941 |
returns | tests/test_laws.py | .py | from returns.context import (
Reader,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.contrib.hypothesis.laws import check_all_laws
from returns.future import Future, FutureResult
from returns.io import IO, IOResult
from returns.maybe import Maybe
from returns.result import Result
chec... | 26 | 578 |
returns | tests/test_pattern_matching.py | .py | import pytest
from returns.io import IO, IOFailure, IOResult, IOSuccess
from returns.maybe import Maybe, Nothing, Some
from returns.result import Failure, Result, Success
@pytest.mark.parametrize(
'container',
[
Success(10),
Success(42),
Failure(RuntimeError()),
Failure(Except... | 83 | 2,609 |
returns | tests/test_iterables/test_fold/test_collect_all.py | .py | import sys
from collections.abc import Iterable, Sequence
import pytest
from returns.context import (
NoDeps,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.future import FutureFailure, FutureResult, FutureSuccess
from returns.io import IOFailure, IOSuccess
from returns.iterables imp... | 186 | 5,927 |
returns | tests/test_iterables/test_fold/test_collect.py | .py | import sys
from collections.abc import Iterable, Sequence
import pytest
from returns.context import (
NoDeps,
Reader,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.future import Future, FutureFailure, FutureResult, FutureSuccess
from returns.io import IO, IOFailure, IOSuccess
fr... | 227 | 7,065 |
returns | tests/test_iterables/test_fold/test_loop.py | .py | import sys
from collections.abc import Iterable
import pytest
from returns.context import (
NoDeps,
Reader,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.future import Future, FutureFailure, FutureResult, FutureSuccess
from returns.io import IO, IOFailure, IOSuccess
from returns... | 245 | 7,447 |
returns | tests/test_contrib/test_hypothesis/test_type_resolution.py | .py | from collections.abc import Callable, Sequence
from typing import Any, TypeVar
import pytest
from hypothesis import given
from hypothesis import strategies as st
from returns.context import (
Reader,
RequiresContext,
RequiresContextFutureResult,
RequiresContextFutureResultE,
RequiresContextIOResul... | 306 | 9,303 |
returns | tests/test_contrib/test_hypothesis/test_type_resolver.py | .py | from typing import Generic, TypeVar
from hypothesis import strategies as st
from returns.contrib.hypothesis.type_resolver import (
look_up_strategy,
strategies_for_types,
)
_ValueType = TypeVar('_ValueType')
class _Wrapper1(Generic[_ValueType]):
_inner_value: _ValueType
class _Wrapper2(Generic[_Value... | 67 | 2,206 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_user_specified_strategy.py | .py | from hypothesis import strategies as st
from test_hypothesis.test_laws import test_custom_type_applicative
from returns.contrib.hypothesis.laws import check_all_laws
container_type = test_custom_type_applicative._Wrapper # noqa: SLF001
check_all_laws(
container_type,
container_strategy=st.builds(container_t... | 12 | 343 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_unsatisfiable_type.py | .py | from collections.abc import Callable
from typing import TypeVar
import pytest
from hypothesis.errors import ResolutionFailed
from returns.contrib.hypothesis.laws import check_all_laws
from returns.interfaces import mappable
from returns.primitives.container import BaseContainer
from returns.primitives.hkt import Supp... | 34 | 911 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_custom_type_with_init.py | .py | from collections.abc import Callable
from typing import TypeVar
from returns.contrib.hypothesis.laws import check_all_laws
from returns.interfaces import equable, mappable
from returns.primitives.container import BaseContainer, container_equality
from returns.primitives.hkt import SupportsKind1
_ValueType = TypeVar('... | 34 | 888 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_wrong_custom_type_with_init.py | .py | from collections.abc import Callable
from typing import TypeVar
import pytest
from returns.contrib.hypothesis.laws import check_all_laws
from returns.interfaces import mappable
from returns.primitives.container import BaseContainer
from returns.primitives.hkt import SupportsKind1
pytestmark = pytest.mark.xfail(raise... | 37 | 925 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_custom_interface_with_laws.py | .py | from abc import abstractmethod
from collections.abc import Callable, Sequence
from typing import ClassVar, Generic, Never, TypeAlias, TypeVar, final
from returns.contrib.hypothesis.laws import check_all_laws
from returns.functions import compose, identity
from returns.primitives.asserts import assert_equal
from return... | 109 | 3,104 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_custom_type_applicative.py | .py | from collections.abc import Callable
from typing import TypeVar
from returns.contrib.hypothesis.laws import check_all_laws
from returns.interfaces import applicative
from returns.primitives.container import BaseContainer
from returns.primitives.hkt import Kind1, SupportsKind1
_ValueType = TypeVar('_ValueType')
_NewVa... | 45 | 1,220 |
returns | tests/test_contrib/test_hypothesis/test_laws/test_custom_strategy_for_callable.py | .py | """
Test that we can register a custom strategy for callables.
We use the strategy to generates `Maybe`s and `Result`s for
`Kind1[_F_Applicative, _SecondType]`.
Without the custom strategy, we would simply get instances of `_Wrapper`, even
though it is not an `Applicative`, because `_Wrapper` is a subtype of `KindN`
... | 162 | 4,727 |
returns | tests/test_contrib/test_pytest/test_plugin_error_handler.py | .py | import pytest
from returns.context import (
RequiresContextFutureResult,
RequiresContextIOResult,
RequiresContextResult,
)
from returns.contrib.pytest import ReturnsAsserts
from returns.functions import identity
from returns.future import FutureResult
from returns.io import IOFailure, IOSuccess
from return... | 106 | 3,307 |
returns | tests/test_contrib/test_pytest/test_plugin_has_trace.py | .py | import pytest
from returns.contrib.pytest import ReturnsAsserts
from returns.io import IOFailure, IOSuccess
from returns.result import Failure, Success, safe
def _create_container_function(container_type, container_value):
return container_type(container_value)
def _create_container_function_intermediate(conta... | 116 | 3,134 |
returns | tests/test_examples/test_maybe/test_maybe_pattern_matching.py | .py | from dataclasses import dataclass
from typing import Final
from returns.maybe import Maybe, Nothing, Some
@dataclass
class _Book:
book_id: int
name: str
_BOOK_LIST: Final = (
_Book(book_id=1, name='Category Theory for Programmers'),
_Book(book_id=2, name='Fluent Python'),
_Book(book_id=3, name=... | 42 | 1,117 |
returns | tests/test_examples/test_io/test_ioresult_container/test_ioresult_pattern_matching.py | .py | from returns.io import IOFailure, IOResult, IOSuccess
from returns.result import Success
container: IOResult[int, str] = IOSuccess(42)
match container:
# Matches if the result stored inside `IOSuccess` is `42`
# We need to use `Success` until the custom matching protocol
# is released. For more information... | 21 | 732 |
returns | tests/test_examples/test_result/test_result_pattern_matching.py | .py | from returns.result import Failure, Success, safe
@safe
def div(first_number: int, second_number: int) -> int:
return first_number // second_number
match div(1, 0):
# Matches if the result stored inside `Success` is `10`
case Success(10):
print('Result is "10"')
# Matches any `Success` inst... | 25 | 698 |
returns | tests/test_examples/test_your_container/test_pair1.py | .py | from collections.abc import Callable
from typing import TypeVar, final
from returns.interfaces import bindable, equable, lashable, swappable
from returns.primitives.container import BaseContainer, container_equality
from returns.primitives.hkt import Kind2, SupportsKind2, dekind
_FirstType = TypeVar('_FirstType')
_Se... | 85 | 2,368 |
returns | tests/test_examples/test_your_container/test_pair3.py | .py | from abc import abstractmethod
from collections.abc import Callable
from typing import Never, TypeVar, final
from returns.interfaces import bindable, equable, lashable, swappable
from returns.primitives.container import BaseContainer, container_equality
from returns.primitives.hkt import Kind2, KindN, SupportsKind2, d... | 210 | 5,966 |
returns | tests/test_examples/test_your_container/test_pair2.py | .py | from abc import abstractmethod
from collections.abc import Callable
from typing import Never, TypeVar, final
from returns.interfaces import bindable, equable, lashable, swappable
from returns.primitives.container import BaseContainer, container_equality
from returns.primitives.hkt import Kind2, KindN, SupportsKind2, d... | 154 | 4,549 |
returns | tests/test_examples/test_your_container/test_pair4.py | .py | from abc import abstractmethod
from collections.abc import Callable, Sequence
from typing import ClassVar, Never, TypeVar, final
from returns.contrib.hypothesis.laws import check_all_laws
from returns.interfaces import bindable, equable, lashable, swappable
from returns.primitives.asserts import assert_equal
from retu... | 250 | 7,318 |
returns | tests/test_examples/test_context/test_reader_future_result.py | .py | from collections.abc import Sequence
from typing import Final, cast
import anyio # you would need to `pip install anyio`
import httpx # you would need to `pip install httpx`
from typing_extensions import TypedDict
from returns.context import RequiresContextFutureResultE
from returns.functions import tap
from return... | 82 | 2,465 |
returns | tests/test_examples/test_future/test_future_result.py | .py | import asyncio # we use `asyncio` only as an example, you can use any io lib
from collections.abc import Sequence
from typing import Final, cast
import httpx # you would need to `pip install httpx`
from typing_extensions import TypedDict
from returns.future import FutureResult, future_safe
from returns.io import IO... | 63 | 1,920 |
returns | tests/test_maybe/test_maybe_unwrap.py | .py | import pytest
from returns.maybe import Nothing, Some
from returns.primitives.exceptions import UnwrapFailedError
def test_unwrap_success():
"""Ensures that unwrap works for Some container."""
assert Some(5).unwrap() == 5
def test_unwrap_failure():
"""Ensures that unwrap works for Nothing container."""... | 16 | 396 |
returns | tests/test_maybe/test_maybe_equality.py | .py | from copy import copy, deepcopy
import pytest
from returns.maybe import Nothing, Some, _Nothing # noqa: PLC2701
from returns.primitives.exceptions import ImmutableStateError
def test_equals():
"""Ensures that ``.equals`` method works correctly."""
inner_value = 1
assert Some(inner_value).equals(Some(i... | 102 | 3,017 |
returns | tests/test_maybe/test_maybe_bind.py | .py | from returns.maybe import Maybe, Nothing, Some
def test_bind_some():
"""Ensures that bind works correctly."""
def factory(inner_value: int) -> Maybe[int]:
return Some(inner_value * 2)
input_value = 5
bound = Some(input_value).bind(factory)
assert bound == factory(input_value)
assert... | 26 | 675 |
returns | tests/test_maybe/test_maybe_conversions.py | .py | from returns.maybe import Nothing, Some
def test_some_is_true() -> None:
"""Ensures that ``Something(...)`` is ``True`` when treated as a boolean."""
assert bool(Some(123))
assert bool(Some('abc'))
def test_nothing_is_false() -> None:
"""Ensures that ``Nothing`` is ``False`` when treated as a boolea... | 24 | 653 |
returns | tests/test_maybe/test_nothing_singleton.py | .py | from returns.maybe import _Nothing # noqa: PLC2701
def test_nothing_singleton():
"""Ensures `_Nothing` is a singleton."""
assert _Nothing() is _Nothing()
| 7 | 165 |
returns | tests/test_maybe/test_maybe_functions/test_maybe_decorator.py | .py | from returns.maybe import Nothing, Some, maybe
@maybe
def _function(hashmap: dict[str, str], key: str) -> str | None:
return hashmap.get(key)
def test_maybe_some():
"""Ensures that maybe decorator works correctly for some case."""
assert _function({'a': 'b'}, 'a') == Some('b')
def test_maybe_nothing()... | 17 | 444 |
returns | tests/test_io/test_ioresult_container/test_ioresult_map.py | .py | from returns.io import IOFailure, IOSuccess
def test_map_iosuccess():
"""Ensures that IOSuccess is mappable."""
assert IOSuccess(5).map(str) == IOSuccess('5')
def test_alt_iofailure():
"""Ensures that IOFailure is mappable."""
assert IOFailure(5).map(str) == IOFailure(5)
assert IOFailure(5).alt(... | 18 | 466 |
returns | tests/test_io/test_ioresult_container/test_ioresulte_cast.py | .py | from returns.io import IOFailure, IOResult, IOResultE, IOSuccess
from returns.pipeline import is_successful
def _function(arg: int) -> IOResultE[float]:
if arg == 0:
return IOFailure(ZeroDivisionError('Divided by 0'))
return IOSuccess(10 / arg)
def test_ioresulte():
"""Ensures that IOResultE cor... | 18 | 512 |
returns | tests/test_io/test_ioresult_container/test_ioresult_values.py | .py | import pytest
from returns.io import IO, IOFailure, IOSuccess
from returns.primitives.exceptions import UnwrapFailedError
def test_ioresult_value_or():
"""Ensures that ``value_or`` works correctly."""
assert IOSuccess(1).value_or(0) == IO(1)
assert IOFailure(1).value_or(0) == IO(0)
def test_unwrap_iosu... | 44 | 1,249 |
returns | tests/test_io/test_ioresult_container/test_ioresult_equals.py | .py | from returns.io import IOFailure, IOSuccess
def test_equals():
"""Ensures that ``.equals`` method works correctly."""
inner_value = 1
assert IOSuccess(inner_value).equals(IOSuccess(inner_value))
assert IOFailure(inner_value).equals(IOFailure(inner_value))
def test_not_equals():
"""Ensures that ... | 20 | 636 |
returns | tests/test_io/test_ioresult_container/test_ioresult_bind.py | .py | from returns.io import IOFailure, IOResult, IOSuccess
from returns.result import Failure, Result, Success
def test_bind():
"""Ensures that bind works."""
def factory(inner_value: int) -> IOResult[int, str]:
if inner_value > 0:
return IOSuccess(inner_value * 2)
return IOFailure(str... | 86 | 2,510 |
returns | tests/test_io/test_ioresult_container/test_ioresult_functions/test_impure_safe.py | .py | import pytest
from returns.io import IOSuccess, impure_safe
@impure_safe
def _function(number: int) -> float:
return number / number
@impure_safe(exceptions=(ZeroDivisionError,))
def _function_two(number: int | str) -> float:
assert isinstance(number, int)
return number / number
@impure_safe((ZeroDiv... | 56 | 1,437 |
returns | tests/test_io/test_io_container/test_io_pickle.py | .py | from returns.io import IO
def test_io_pickle():
"""Tests how pickle protocol works for containers."""
assert IO(1).__getstate__() == {'container_value': 1}
def test_io_pickle_restore():
"""Ensures that object can be restored."""
container = IO(2)
container.__setstate__({'container_value': 1})
... | 14 | 348 |
returns | tests/test_io/test_io_container/test_io_equality.py | .py | from returns.io import IO
def test_equals():
"""Ensures that ``.equals`` method works correctly."""
assert IO(1).equals(IO(1))
assert IO(1).equals(IO.from_value(1))
def test_not_equals():
"""Ensures that ``.equals`` method works correctly."""
assert not IO(1).equals(IO('a'))
def test_equality(... | 27 | 644 |
returns | tests/test_io/test_io_container/test_io.py | .py | import pytest
from returns.io import IO, IOFailure, IOResult, IOSuccess
def test_io_map():
"""Ensures that IO container supports ``.map()`` method."""
io: IO[float] = IO(1).map(
lambda number: number / 2,
)
assert io == IO(0.5)
def test_io_bind():
"""Ensures that IO container supports ... | 41 | 892 |
returns | tests/test_io/test_io_container/test_io_functions/test_impure.py | .py | from returns.io import IO, impure
def _fake_impure_function(some_param: int) -> int:
return some_param
def test_impure():
"""Ensures that impure returns IO container."""
impure_result = impure(_fake_impure_function)(1)
assert isinstance(impure_result, IO)
assert impure_result == IO(1)
| 13 | 310 |
returns | tests/test_methods/test_partition.py | .py | import pytest
from returns.io import IO, IOResult
from returns.maybe import Nothing, Some
from returns.methods import partition
from returns.result import Failure, Success
@pytest.mark.parametrize(
('containers', 'expected'),
[
(
(Success(1), Success(2), Failure(None), Success(3)),
... | 35 | 881 |
returns | tests/test_result/test_result_error.py | .py | from returns.result import Failure, ResultE, Success
def test_result_error_success():
"""Ensures that ResultE can be typecasted to success."""
container: ResultE[int] = Success(1)
assert container.unwrap() == 1
def test_result_error_failure():
"""Ensures that ResultE can be typecasted to failure."""... | 14 | 419 |
returns | tests/test_result/test_result_value_or.py | .py | from returns.result import Failure, Success
def test_success_value():
"""Ensures that value is fetch correctly from the Success."""
bound = Success(5).value_or(None)
assert bound == 5
def test_failure_value():
"""Ensures that value is fetch correctly from the Failure."""
bound = Failure(1).valu... | 16 | 371 |
returns | tests/test_result/test_result_failure.py | .py | import pytest
from returns.primitives.exceptions import UnwrapFailedError
from returns.result import Failure, Success
def test_unwrap_success():
"""Ensures that unwrap works for Success container."""
with pytest.raises(UnwrapFailedError):
assert Success(5).failure()
def test_unwrap_failure():
"... | 16 | 411 |
returns | tests/test_result/test_result_bind.py | .py | from returns.result import Failure, Result, Success
def test_bind():
"""Ensures that bind works."""
def factory(inner_value: int) -> Result[int, str]:
if inner_value > 0:
return Success(inner_value * 2)
return Failure(str(inner_value))
input_value = 5
bound: Result[int, s... | 77 | 2,189 |
returns | tests/test_result/test_result_equality.py | .py | from copy import copy, deepcopy
import pytest
from returns.primitives.exceptions import ImmutableStateError
from returns.result import Failure, Success
def test_equals():
"""Ensures that ``.equals`` method works correctly."""
inner_value = 1
assert Success(inner_value).equals(Success(inner_value))
... | 100 | 2,996 |
returns | tests/test_result/test_result_map.py | .py | from returns.result import Failure, Success
def test_map_success():
"""Ensures that Success is mappable."""
assert Success(5).map(str) == Success('5')
def test_alt_failure():
"""Ensures that Failure is mappable."""
assert Failure(5).map(str) == Failure(5)
assert Failure(5).alt(str) == Failure('5... | 18 | 438 |
returns | tests/test_result/test_result_unwrap.py | .py | import pytest
from returns.primitives.exceptions import UnwrapFailedError
from returns.result import Failure, Success
def test_unwrap_success():
"""Ensures that unwrap works for Success container."""
assert Success(5).unwrap() == 5
def test_unwrap_failure():
"""Ensures that unwrap works for Failure con... | 27 | 752 |
returns | tests/test_result/test_result_functions/test_safe.py | .py | import pytest
from returns.result import Success, safe
@safe
def _function(number: int) -> float:
return number / number
@safe(exceptions=(ZeroDivisionError,))
def _function_two(number: int | str) -> float:
assert isinstance(number, int)
return number / number
@safe((ZeroDivisionError,)) # no name
d... | 47 | 1,245 |
returns | tests/test_pipeline/test_is_successful.py | .py | import pytest
from returns.io import IOFailure, IOSuccess
from returns.maybe import Nothing, Some
from returns.pipeline import is_successful
from returns.result import Failure, Success
@pytest.mark.parametrize(
('container', 'correct_result'),
[
(Success('a'), True),
(Failure('a'), False),
... | 24 | 635 |
returns | tests/test_pipeline/test_managed/test_managed_ioresult.py | .py | import pytest
from returns.io import IOFailure, IOResult, IOSuccess
from returns.pipeline import managed
from returns.result import Failure, Result, Success
_acquire_success = IOSuccess('acquire success')
_acquire_failure = IOFailure('acquire failure')
def _use_success(inner_value: str) -> IOResult[str, str]:
r... | 129 | 3,322 |
returns | tests/test_pipeline/test_managed/test_managed_future_result.py | .py | import pytest
from returns.future import FutureResult
from returns.io import IOFailure, IOSuccess
from returns.pipeline import managed
from returns.result import Failure, Result, Success
def _acquire_success() -> FutureResult[str, str]:
return FutureResult.from_value('acquire success')
def _acquire_failure() -... | 137 | 3,611 |
returns | tests/test_pipeline/test_managed/test_managed_reader_future_result.py | .py | import pytest
from returns.context import NoDeps, ReaderFutureResult
from returns.io import IOFailure, IOSuccess
from returns.pipeline import managed
from returns.result import Failure, Result, Success
def _acquire_success() -> ReaderFutureResult[str, str, NoDeps]:
return ReaderFutureResult.from_value('acquire s... | 138 | 3,820 |
returns | tests/test_pipeline/test_managed/test_managed_reader_ioresult.py | .py | import pytest
from returns.context import NoDeps, ReaderIOResult
from returns.io import IOFailure, IOSuccess
from returns.pipeline import managed
from returns.result import Failure, Result, Success
_acquire_success = ReaderIOResult.from_value('acquire success')
_acquire_failure = ReaderIOResult.from_failure('acquire ... | 130 | 3,569 |
returns | tests/test_unsafe/test_unsafe_perform_io.py | .py | from returns.io import IO
from returns.unsafe import unsafe_perform_io
def test_unsafe_perform_io():
"""Ensures that unsafe_perform_io returns the object itself."""
id_object = object()
assert unsafe_perform_io(IO(id_object)) is id_object
| 9 | 253 |
returns | tests/test_curry/test_curry.py | .py | from inspect import getdoc
import pytest
from returns.curry import curry
def test_docstring():
"""Ensures that we preserve docstrings from curried function."""
@curry
def factory(arg: int, other: int) -> None:
"""Some docstring."""
assert getdoc(factory) == 'Some docstring.'
def test_imm... | 195 | 4,754 |
returns | tests/test_functions/test_compose.py | .py | from returns.functions import compose
def _first(argument: int) -> str:
return str(argument)
def _second(argument: str) -> bool:
return bool(argument)
def test_function_composition():
"""Ensures that functions can be composed and return type is correct."""
second_after_first = compose(_first, _sec... | 18 | 408 |
returns | tests/test_functions/test_raise_exception.py | .py | import pytest
from returns.functions import raise_exception
from returns.result import Failure, Success
class _CustomError(Exception):
"""Just for the test."""
@pytest.mark.parametrize(
'exception_type',
[
TypeError,
ValueError,
_CustomError,
],
)
def test_raise_regular_exce... | 35 | 877 |
returns | tests/test_primitives/test_laws/test_lawful/test_laws_resolution.py | .py | import pytest
from test_hypothesis.test_laws import (
test_custom_interface_with_laws,
test_custom_type_applicative,
)
from returns.context import (
RequiresContext,
RequiresContextFutureResult,
RequiresContextIOResult,
RequiresContextResult,
)
from returns.future import Future, FutureResult
fr... | 79 | 2,479 |
returns | tests/test_primitives/test_asserts/test_assert_equal.py | .py | from collections.abc import Sequence
import pytest
from returns.context import (
Reader,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.contrib.pytest import ReturnsAsserts
from returns.future import Future, FutureResult
from returns.io import IO, IOResult
from returns.maybe import M... | 81 | 2,289 |
returns | tests/test_primitives/test_container/test_base_container/test_pickle_backward_deserialization.py | .py | import pickle # noqa: S403
from returns.primitives.container import BaseContainer
def test_pickle_backward_deserialization():
"""Test that BaseContainer can be deserialized from 0.19.0 and earlier."""
# BaseContainer(1) serialized as of 0.19.0
serialized_container = (
b'\x80\x04\x958\x00\x00\x00... | 15 | 539 |
returns | tests/test_primitives/test_container/test_base_container/test_pickle.py | .py | import pickle # noqa: S403
from typing import Any
from hypothesis import example, given
from hypothesis import strategies as st
from returns.primitives.container import BaseContainer
class _CustomClass:
def __init__(self, inner_value: Any) -> None:
self.inner_value = inner_value
def __eq__(self, o... | 40 | 1,044 |
returns | tests/test_primitives/test_exceptions/test_pickle_unwrap_failed_error.py | .py | import pickle # noqa: S403
from returns.maybe import Nothing
from returns.primitives.exceptions import UnwrapFailedError
from returns.result import Failure
def test_pickle_unwrap_failed_error_from_maybe():
"""Ensures that UnwrapFailedError with Maybe can be pickled."""
serialized = None
try:
Not... | 30 | 1,010 |
returns | tests/test_converters/test_flatten.py | .py | import pytest
from returns.context import (
RequiresContext,
RequiresContextFutureResult,
RequiresContextIOResult,
RequiresContextResult,
)
from returns.converters import flatten
from returns.future import Future, FutureResult
from returns.io import IO, IOFailure, IOSuccess
from returns.maybe import No... | 138 | 4,216 |
returns | tests/test_context/test_requires_context_ioresult/test_requires_context_ioresult_bind.py | .py | from returns.context import RequiresContext, RequiresContextResult
from returns.context import RequiresContextIOResult as RCR # noqa: N814
from returns.io import IOFailure, IOResult, IOSuccess
from returns.result import Failure, Result, Success
def test_bind():
"""Ensures that bind works."""
def factory(inn... | 123 | 3,869 |
returns | tests/test_context/test_requires_context_ioresult/test_context_ioresult.py | .py | from copy import copy, deepcopy
import pytest
from returns.context import RequiresContextIOResult
from returns.primitives.exceptions import ImmutableStateError
def test_requires_context_result_immutable():
"""Ensures that container is immutable."""
with pytest.raises(ImmutableStateError):
RequiresCo... | 25 | 872 |
returns | tests/test_context/test_requires_context_ioresult/test_requires_context_ioresult_cast.py | .py | from returns.context import (
ReaderIOResult,
ReaderIOResultE,
RequiresContextIOResult,
RequiresContextIOResultE,
)
def _function(arg: int) -> RequiresContextIOResultE[float, int]:
if arg == 0:
return RequiresContextIOResult.from_failure(
ZeroDivisionError('Divided by 0'),
... | 34 | 1,185 |
returns | tests/test_context/test_requires_context_ioresult/test_requires_context_ioresult.py | .py | from returns.context import RequiresContextIOResultE
from returns.io import IOSuccess
def test_regression394():
"""
It used to raise ``ImmutableStateError`` for type aliases.
Here we use the minimal reproduction sample.
.. code:: python
Traceback (most recent call last):
File "ex.py",... | 28 | 912 |
returns | tests/test_context/test_requires_context/test_context_equality.py | .py | from collections.abc import Callable
from returns.context import RequiresContext
def _same_function(some_arg: int) -> Callable[[float], float]:
return lambda other: other / some_arg
def test_equality() -> None:
"""Ensures that containers can be compared."""
assert RequiresContext(_same_function) == Req... | 19 | 575 |
returns | tests/test_context/test_requires_context/test_context.py | .py | from copy import copy, deepcopy
import pytest
from returns.context import RequiresContext
from returns.primitives.exceptions import ImmutableStateError
def test_requires_context_immutable() -> None:
"""Ensures that Context is immutable."""
with pytest.raises(ImmutableStateError):
RequiresContext.fro... | 25 | 773 |
returns | tests/test_context/test_requires_context/test_context_utils.py | .py | from returns.context import RequiresContext
def test_context_ask():
"""Ensures that ``ask`` method works correctly."""
assert RequiresContext[str, int].ask()(1) == 1
assert RequiresContext[int, str].ask()('a') == 'a'
def test_requires_context_from_value():
"""Ensures that ``from_value`` method works... | 14 | 455 |
returns | tests/test_context/test_requires_context_result/test_requires_context_result_cast.py | .py | from returns.context import (
ReaderResult,
ReaderResultE,
RequiresContextResult,
RequiresContextResultE,
)
def _function(arg: int) -> RequiresContextResultE[float, int]:
if arg == 0:
return RequiresContextResult.from_failure(
ZeroDivisionError('Divided by 0'),
)
re... | 34 | 1,144 |
returns | tests/test_context/test_requires_context_result/test_requires_context_result_bind.py | .py | from returns.context import RequiresContext
from returns.context import RequiresContextResult as RCR # noqa: N817
from returns.result import Failure, Result, Success
def test_bind():
"""Ensures that bind works."""
def factory(inner_value: int) -> RCR[float, str, int]:
if inner_value > 0:
... | 88 | 2,593 |
returns | tests/test_context/test_requires_context_result/test_context_result.py | .py | from copy import copy, deepcopy
import pytest
from returns.context import RequiresContextResult
from returns.primitives.exceptions import ImmutableStateError
def test_immutable_copy():
"""Ensures that helper returns it self when passed to copy function."""
context_result = RequiresContextResult.from_value(1... | 25 | 788 |
returns | tests/test_future/test_future_result/test_future_result_units.py | .py | import pytest
from returns.future import Future, FutureResult
from returns.io import IO, IOFailure, IOSuccess
from returns.result import Failure, Success
@pytest.mark.anyio
async def test_inner_value(subtests):
"""Ensure that coroutine correct value is preserved for all units."""
containers = [
# We ... | 31 | 1,246 |
returns | tests/test_future/test_future_result/test_future_result_equality.py | .py | import pytest
from returns.future import FutureResult
def test_nonequality():
"""Ensures that containers can be compared."""
assert FutureResult.from_value(1) != FutureResult.from_value(1)
assert hash(FutureResult.from_value(1))
@pytest.mark.anyio
async def test_equality():
"""Ensures that containe... | 18 | 457 |
returns | tests/test_future/test_future_result/test_future_result_decorator.py | .py | import anyio
import pytest
from returns.future import FutureResult, future_safe
from returns.io import IOFailure, IOSuccess
@future_safe
async def _coro(arg: int) -> float:
assert isinstance(arg, int)
await anyio.sleep(0)
return 1 / arg
@future_safe(exceptions=(ZeroDivisionError,))
async def _coro_two(... | 64 | 1,822 |
returns | tests/test_future/test_future_container/test_future_equality.py | .py | import pytest
from returns.future import Future
def test_nonequality():
"""Ensures that containers can be compared."""
assert Future.from_value(1) != Future.from_value(1)
assert hash(Future.from_value(1))
@pytest.mark.anyio
async def test_equality():
"""Ensures that containers are not compared to r... | 16 | 406 |
returns | tests/test_future/test_future_container/test_future_units.py | .py | from collections.abc import Awaitable
from typing import Any
import pytest
from returns.future import Future, FutureResult
from returns.io import IO
@pytest.mark.anyio
async def test_inner_value(subtests):
"""Ensure that coroutine correct value is preserved for all units."""
containers: list[Awaitable[Any]]... | 25 | 851 |
returns | tests/test_future/test_future_container/test_asyncize_decorator.py | .py | import pytest
from returns.future import asyncify
@asyncify
def _function(arg: int) -> float:
return arg / 2
@pytest.mark.anyio
async def test_asyncify_decorator():
"""Ensure that function marked with ``@asyncify`` is awaitable."""
coro = _function(2)
assert await coro == 1
| 17 | 297 |
returns | tests/test_future/test_future_container/test_future_decorator.py | .py | import anyio
import pytest
from returns.future import Future, future
from returns.io import IO
@future
async def _coro(arg: int) -> float:
assert isinstance(arg, int)
await anyio.sleep(0)
return arg / 2
@pytest.mark.anyio
async def test_safe_decorator():
"""Ensure that coroutine marked with ``@futu... | 22 | 471 |
returns | tests/test_trampolines/test_trampoline_decorator.py | .py | import sys
from collections.abc import Callable, Iterator
import pytest
from returns.trampolines import Trampoline, trampoline
@trampoline
def _accumulate(
numbers: Iterator[int],
acc: int = 0,
) -> int | Trampoline[int]:
number = next(numbers, None)
if number is None:
return acc
return ... | 57 | 1,297 |
returns | returns/unsafe.py | .py | 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 :class:`returns.io.IO` container.
Sh... | 32 | 829 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.