1
1
from enum import Enum
2
2
3
3
from pydantic import BaseModel
4
- from pydantic .fields import ModelField
5
4
6
5
from easyconfig .__const__ import ARG_NAME_IN_FILE , MISSING
7
6
from easyconfig .yaml import CommentedMap , CommentedSeq
10
9
11
10
12
11
def _get_yaml_value (obj , parent_model : BaseModel , skip_none = True ):
12
+ if obj is None :
13
+ return None
14
+
13
15
# Sometimes enum is used with int/str
14
16
if isinstance (obj , Enum ):
15
17
return _get_yaml_value (obj .value , parent_model = parent_model , skip_none = skip_none )
16
18
17
19
# yaml native datatypes
18
- if isinstance (obj , (int , float , str , bool , bytes , NoneType )):
19
- return obj
20
+ # Pydantic defines several validators that inherit from the python base type
21
+ # Yaml can't represent those, so we cast them back to the native data type.
22
+ for data_type in (int , float , str , bool , bytes ):
23
+ if isinstance (obj , data_type ):
24
+ return data_type (obj )
20
25
21
26
if isinstance (obj , BaseModel ):
22
27
return cmap_from_model (obj , skip_none = skip_none )
@@ -43,7 +48,7 @@ def _get_yaml_value(obj, parent_model: BaseModel, skip_none=True):
43
48
44
49
def cmap_from_model (model : BaseModel , skip_none = True ) -> CommentedMap :
45
50
cmap = CommentedMap ()
46
- for obj_key , field in model .__fields__ .items (): # type: str, ModelField
51
+ for obj_key , field in model .__fields__ .items ():
47
52
value = getattr (model , obj_key , MISSING )
48
53
if value is MISSING or (skip_none and value is None ):
49
54
continue
0 commit comments