1616
1717import dataclasses
1818import json
19- from typing import Optional
19+ from typing import Any , Optional
2020
2121
2222_JSON_SEPARATORS = (',' , ':' )
@@ -130,11 +130,10 @@ def __post_init__(self):
130130
131131 def __repr__ (self ) -> str :
132132 properties = []
133- for key , value in self .__dict__ .items ():
134- if value is not None :
135- if isinstance (value , float ):
136- value = f'{ value :.3f} '
137- properties .append (f'{ key } ={ value !r} ' )
133+ for key , value in self .as_dict (skip_none = True ).items ():
134+ if isinstance (value , float ):
135+ value = f'{ value :.3f} '
136+ properties .append (f'{ key } ={ value !r} ' )
138137 return f"JSONAction({ ', ' .join (properties )} )"
139138
140139 def __eq__ (self , other ):
@@ -145,11 +144,24 @@ def __eq__(self, other):
145144 def __ne__ (self , other ):
146145 return not self .__eq__ (other )
147146
148- def json_str (self ) -> str :
147+ def as_dict (self , skip_none : bool = True ) -> dict [str , Any ]:
148+ """Returns a dict representation of the action.
149+
150+ Args:
151+ skip_none: Whether to skip none values.
152+ Returns:
153+ A dict representation of the action.
154+ """
149155 non_null = {}
150156 for key , value in self .__dict__ .items ():
151157 if value is not None :
158+ if skip_none and value is None :
159+ continue
152160 non_null [key ] = value
161+ return non_null
162+
163+ def json_str (self ) -> str :
164+ non_null = self .as_dict (skip_none = True )
153165 return json .dumps (non_null , separators = _JSON_SEPARATORS )
154166
155167
0 commit comments