Skip to content

Commit

Permalink
Add static method from_optional
Browse files Browse the repository at this point in the history
  • Loading branch information
check69 committed Nov 23, 2023
1 parent fa8d8e2 commit ea8fb4d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
9 changes: 8 additions & 1 deletion 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
try:
from pydantic.fields import ModelField
Expand Down Expand Up @@ -324,6 +324,13 @@ def __validate_dict(cls, value: Dict, field: "ModelField"):

return Some(valid_value)

@staticmethod
def from_optional(value: Optional[T]) -> "Option[T]":
if value is None:
return Empty()

return Some(value)


@dataclass(eq=True, frozen=True)
class Some(OptionProtocol[T]):
Expand Down
8 changes: 8 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,11 @@ def test_option_contains():
def test_option_iter():
assert list(iter(Empty())) == []
assert list(iter(Some(1))) == [1]


def test_from_optional():
assert Some(0) == OptionProtocol.from_optional(0)
assert Empty() == OptionProtocol.from_optional(None)
example_dictionary = {"data": 5}
assert Empty() == OptionProtocol.from_optional(example_dictionary.get("key_not_found"))
assert Some(5) == OptionProtocol.from_optional(example_dictionary.get("data"))

0 comments on commit ea8fb4d

Please sign in to comment.