Skip to content

Commit

Permalink
Move Option.from_optional to option_from function.
Browse files Browse the repository at this point in the history
  • Loading branch information
AlejandroCabeza committed Sep 2, 2024
1 parent ea8fb4d commit 6a090f6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
17 changes: 10 additions & 7 deletions rusty_results/prelude.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,13 +324,6 @@ 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 Expand Up @@ -522,6 +515,16 @@ def __get_validators__(cls):
Option = Union[Some[T], Empty]


def option_from[T](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
15 changes: 10 additions & 5 deletions rusty_results/tests/option/test_option.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@ def test_option_iter():
assert list(iter(Some(1))) == [1]


def test_from_optional():
assert Some(0) == OptionProtocol.from_optional(0)
assert Empty() == OptionProtocol.from_optional(None)
def test_option_from():
assert Some(0) == option_from(0)
assert Empty() == option_from(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"))
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 6a090f6

Please sign in to comment.