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

Add static method from_optional #20

Merged
merged 7 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 4 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ jobs:
- name: Build coverage file
run: pytest --cache-clear --cov=rusty_results --cov-report=xml:pytest-coverage.xml ./rusty_results
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
uses: codecov/codecov-action@v4
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
with:
files: ./pytest-coverage.xml
fail_ci_if_error: true
fail_ci_if_error: true
3 changes: 2 additions & 1 deletion examples/patmat_option.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""
Example on pattern matching handling of Option
"""
from typing import List

from rusty_results import Option, Some, Empty


def find_index(l: [str], value: str) -> Option[int]:
def find_index(l: List[str], value: str) -> Option[int]:
for i, e in enumerate(l):
if e == value:
return Some(i)
Expand Down
14 changes: 12 additions & 2 deletions rusty_results/prelude.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from abc import abstractmethod
from dataclasses import dataclass
from typing import cast, TypeVar, Union, Callable, Generic, Iterator, Tuple, Dict, Any
from typing import cast, TypeVar, Union, Callable, Generic, Iterator, Tuple, Dict, Any, Optional
from rusty_results.exceptions import UnwrapException, EarlyReturnException

try:
Expand Down Expand Up @@ -540,6 +540,16 @@ def __get_validators__(cls):
Option = Union[Some[T], Empty]


def option_from(value: Optional[T]) -> Option[T]:
"""
:param value: Value from any type to be converted to an Option
:return: The value wrapped in an Option or the original Option if it is already an Option
"""
if value is None:
return Empty()
return Some(value).flatten_one()


class ResultProtocol(Generic[T, E]):
@property
@abstractmethod
Expand Down Expand Up @@ -1043,4 +1053,4 @@ def __get_validators__(cls):
yield from ResultProtocol.__get_validators__()


Result = Union[Ok[T, E], Err[T, E]]
Result = Union[Ok[T, E], Err[T, E]]
13 changes: 13 additions & 0 deletions rusty_results/tests/option/test_option.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,16 @@ def test_option_contains():
def test_option_iter():
assert list(iter(Empty())) == []
assert list(iter(Some(1))) == [1]


def test_option_from():
assert Some(0) == option_from(0)
assert Empty() == option_from(None)
example_dictionary = {"data": 5}
assert Empty() == option_from(example_dictionary.get("key_not_found"))
assert Some(5) == option_from(example_dictionary.get("data"))
opt = Some(3)
assert opt == option_from(opt)
assert Empty() == option_from(Empty())
nested_opt = Some(Some(Some(Some(3))))
assert nested_opt == option_from(nested_opt)
Loading