Skip to content

Commit

Permalink
Add static method from_optional (#20)
Browse files Browse the repository at this point in the history
* Add static method from_optional

* Move Option.from_optional to option_from function.

* Fix mypy List typing.

* Update prelude.py

Undo remove line jump.

* Remove incompatible generic type on option_from.

* Update codecov action and include token.

---------

Co-authored-by: Álex Cabeza Romero <[email protected]>
  • Loading branch information
check69 and AlejandroCabeza committed Sep 2, 2024
1 parent fcace3a commit 8a47e13
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 5 deletions.
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)

0 comments on commit 8a47e13

Please sign in to comment.