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

23 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2025-08-19 20:24 -0700

1from typing import Optional, Callable, Any, TypeVar 

2from .option import Option as OptionType 

3 

4T = TypeVar('T') 

5 

6 

7def 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 

18def 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 

25def 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()