11"""Queenbee utility functions."""
22import hashlib
33import json
4- from typing import List , Dict , Any
4+ from typing import List , Union , Dict , Any
55
66import yaml
77from pydantic import BaseModel as PydanticBaseModel
8- from pydantic import validator , Field , constr
8+ from pydantic import Field , field_validator , ValidationError
99
1010from .parser import parse_file
1111from .variable import get_ref_variable
@@ -30,37 +30,42 @@ class BaseModelNoType(PydanticBaseModel):
3030 extensions.
3131 """
3232
33- def yaml (self , exclude_unset = False , ** kwargs ):
33+ def yaml (self , exclude_defaults : bool = False , exclude_none : bool = False , ** kwargs ):
3434 """Get a YAML string from the model
3535
3636 Keyword Arguments:
37- exclude_unset {bool} -- Boolean toggle to add or remove any unset/None values
38- (default: {False})
37+ exclude_defaults {bool} -- Whether to exclude fields that are set to their
38+ default values. (default: {False})
3939
4040 Returns:
4141 str -- A yaml string representing the model
4242 """
43+ data = self .model_dump (
44+ mode = 'json' , by_alias = True , exclude_defaults = exclude_defaults , exclude_none = exclude_none , ** kwargs
45+ )
4346 return yaml .dump (
44- json .loads (self .json (by_alias = True ,
45- exclude_unset = exclude_unset , ** kwargs )),
47+ data ,
4648 default_flow_style = False
4749 )
4850
49- def to_dict (self , exclude_unset = False , by_alias = True , ** kwargs ):
51+ def to_dict (self , exclude_defaults : bool = False , by_alias : bool = True , exclude_none : bool = False , ** kwargs ):
5052 """Get a dictionary from the model
5153
5254 Keyword Arguments:
53- exclude_unset {bool} -- Boolean toggle to add or remove any unset/None values
55+ exclude_defaults {bool} -- Whether to exclude fields that are set to their
56+ default values.
5457 (default: {False})
5558 by_alias {bool} -- Boolean toggle to use attribute alias or attribute names
5659 as key (default: {True})
5760
5861 Returns:
5962 dict -- A python dictionary representing the model
6063 """
61- return json .loads (self .json (by_alias = by_alias , exclude_unset = exclude_unset , ** kwargs ))
64+ return self .model_dump (
65+ mode = 'json' , by_alias = by_alias , exclude_defaults = exclude_defaults , exclude_none = exclude_none , ** kwargs
66+ )
6267
63- def to_json (self , filepath , indent = None , ** kwargs ):
68+ def to_json (self , filepath : str , indent : int = None , ** kwargs ):
6469 """Write a JSON file of the model
6570
6671 Arguments:
@@ -70,20 +75,19 @@ def to_json(self, filepath, indent=None, **kwargs):
7075 indent {int} -- indent amount (default: {None})
7176 """
7277 with open (filepath , 'w' ) as file :
73- file .write (self .json (by_alias = True , exclude_unset = False ,
74- indent = indent , ** kwargs ))
78+ file .write (self .model_dump_json (by_alias = True , indent = indent , exclude_none = True , ** kwargs ))
7579
76- def to_yaml (self , filepath , exclude_unset = False , ** kwargs ):
80+ def to_yaml (self , filepath : str , exclude_defaults : bool = False , exclude_none : bool = True , ** kwargs ):
7781 """Write a YAML file of the model
7882
7983 Arguments:
8084 filepath {str} -- Path to the file to be written
8185
8286 Keyword Arguments:
83- exclude_unset {bool} -- Boolean toggle to add or remove any unset/None values
84- (default: {False})
87+ exclude_defaults {bool} -- Whether to exclude fields that are set to their
88+ default values. (default: {False})
8589 """
86- content = self .yaml (exclude_unset = exclude_unset , ** kwargs )
90+ content = self .yaml (exclude_defaults = exclude_defaults , exclude_none = exclude_none , ** kwargs )
8791
8892 with open (filepath , 'w' ) as out_file :
8993 out_file .write (content )
@@ -99,7 +103,10 @@ def from_file(cls, filepath):
99103 cls -- An instance of the pydantic class
100104 """
101105 data = parse_file (filepath )
102- return cls .parse_obj (data )
106+ try :
107+ return cls .model_validate (data )
108+ except ValidationError as e :
109+ raise ValueError (e ) from e
103110
104111 def __repr__ (self ):
105112 return self .yaml ()
@@ -112,7 +119,7 @@ def __hash__(self):
112119 str -- A hash/digest of the model
113120 """
114121 return hashlib .sha256 (
115- self .json (by_alias = True , exclude_unset = False ).encode ('utf-8' )
122+ self .model_dump_json (by_alias = True , exclude_none = True ).encode ('utf-8' )
116123 ).hexdigest ()
117124
118125 def _referenced_values (self , var_names : List [str ]) -> Dict [str , List [str ]]:
@@ -143,16 +150,17 @@ def _referenced_values(self, var_names: List[str]) -> Dict[str, List[str]]:
143150class BaseModel (BaseModelNoType ):
144151 """BaseModel with functionality to return the object as a yaml string."""
145152
146- type : constr ( regex = '^ BaseModel$' ) = ' BaseModel'
153+ type : str = Field ( ' BaseModel' , pattern = '^ BaseModel$' )
147154
148155 annotations : Dict [str , Any ] = Field (
149- None ,
156+ default_factory = dict ,
150157 description = 'An optional dictionary to add annotations to inputs. These '
151158 'annotations will be used by the client side libraries.'
152159 )
153160
154- @validator ('type' )
155- def ensure_type_match (cls , v ):
161+ @field_validator ('type' )
162+ @classmethod
163+ def ensure_type_match (cls , v : str ) -> str :
156164 name = cls .__name__
157165 if name != v :
158166 raise ValueError (
@@ -161,7 +169,3 @@ def ensure_type_match(cls, v):
161169 f'Pydantic object. In this case: { name } '
162170 )
163171 return v
164-
165- @validator ('annotations' , always = True )
166- def replace_none_value (cls , v ):
167- return {} if not v else v
0 commit comments