Coverage for src/monadc/utils.py: 100%

1 from typing import Optional, Callable, Any, TypeVar

2 from .option import Option as OptionType

3

4 T = TypeVar('T')

5

6

7 def from_callable(func: Callable[[], T]) -> OptionType[T]:

8 """Create an Option by calling a function. Exceptions result in Nil."""

9 try:

10 result = func()

11 from .option import Option

12 return Option(result)

13 except Exception:

14 from .option import Nil

15 return Nil()

16

17

18 def from_dict_get(dictionary: dict, key: Any, default: Optional[T] = None) -> OptionType[T]:

19 """Create an Option from dict.get()."""

20 value = dictionary.get(key, default)

21 from .option import Option

22 return Option(value)

23

24

25 def from_getattr(obj: Any, attr: str, default: Optional[T] = None) -> OptionType[T]:

26 """Create an Option from getattr()."""

27 try:

28 value = getattr(obj, attr, default)

29 from .option import Option

30 return Option(value)

31 except Exception:

32 from .option import Nil

33 return Nil()