Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/cattrs/enums.py: 40%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

15 statements  

1from collections.abc import Callable 

2from enum import Enum 

3from typing import TYPE_CHECKING, Any 

4 

5if TYPE_CHECKING: 

6 from .converters import BaseConverter 

7 

8 

9def enum_unstructure_factory( 

10 type: type[Enum], converter: "BaseConverter" 

11) -> Callable[[Enum], Any]: 

12 """A factory for generating enum unstructure hooks. 

13 

14 If the enum is a typed enum (has `_value_`), we use the underlying value's hook. 

15 Otherwise, we use the value directly. 

16 """ 

17 if "_value_" in type.__annotations__: 

18 return lambda e: converter.unstructure(e.value) 

19 

20 return lambda e: e.value 

21 

22 

23def enum_structure_factory( 

24 type: type[Enum], converter: "BaseConverter" 

25) -> Callable[[Any, type[Enum]], Enum]: 

26 """A factory for generating enum structure hooks. 

27 

28 If the enum is a typed enum (has `_value_`), we structure the value first. 

29 Otherwise, we use the value directly. 

30 """ 

31 if "_value_" in type.__annotations__: 

32 val_type = type.__annotations__["_value_"] 

33 val_hook = converter.get_structure_hook(val_type) 

34 return lambda v, _: type(val_hook(v, val_type)) 

35 

36 return lambda v, _: type(v)