From ea8fb4d011859286ad25cb07cc615de0a301aac2 Mon Sep 17 00:00:00 2001 From: check69 Date: Thu, 23 Nov 2023 00:05:43 +0000 Subject: [PATCH] Add static method from_optional --- rusty_results/prelude.py | 9 ++++++++- rusty_results/tests/option/test_option.py | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/rusty_results/prelude.py b/rusty_results/prelude.py index c7d703d..df86d0e 100644 --- a/rusty_results/prelude.py +++ b/rusty_results/prelude.py @@ -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 @@ -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]): diff --git a/rusty_results/tests/option/test_option.py b/rusty_results/tests/option/test_option.py index 30d860c..35e354d 100644 --- a/rusty_results/tests/option/test_option.py +++ b/rusty_results/tests/option/test_option.py @@ -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"))