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 1 commit
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
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)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should use the type alias Option instead of the protocol for this calls. They are a bad example 😅

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated to option_from function.

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"))
Loading