Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Adds validate function #584

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions returns/_internal/pipeline/validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from typing import Callable, Iterable, Sequence, Type, TypeVar

from returns._internal.iterable import internal_iterable_kind
from returns.interfaces.specific.result import ResultLikeN
from returns.primitives.hkt import Kinded, KindN, kinded
from returns.primitives.iterables import CollectAll

# Definitions:
_FirstType = TypeVar('_FirstType', contravariant=True)
_SecondType = TypeVar('_SecondType')
_ThirdType = TypeVar('_ThirdType')

_ResultKind = TypeVar('_ResultKind', bound=ResultLikeN)


def validate( # noqa: WPS234
container_type: Type[_ResultKind],
steps: Iterable[
Callable[
[_FirstType],
KindN[_ResultKind, _FirstType, _SecondType, _ThirdType],
]
],
) -> Kinded[Callable[
[_FirstType],
KindN[_ResultKind, _FirstType, Sequence[_SecondType], _ThirdType],
]]:
"""
Functional validation.

Works with any ``ResultLikeN`` type.
"""

@kinded
def factory(instance: _FirstType) -> KindN[
_ResultKind,
_FirstType,
Sequence[_SecondType],
_ThirdType,
]:
if not steps:
return container_type.from_value(instance)

swapped = [step(instance).swap() for step in steps]
return internal_iterable_kind(
container_type, swapped, CollectAll,
).bind(
lambda errors: container_type.from_value(errors)
if errors else container_type.from_failure(errors),
).swap()
return factory