-
Notifications
You must be signed in to change notification settings - Fork 3
Implement line as a list of dict #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
But the name is written twice then, which is redundant. Also, why not ? |
|
Discussed: same problem as #12 (comment) |
| @model_serializer | ||
| def _serialize(self): | ||
| data = self.__dict__.copy() | ||
| data.pop("name", None) | ||
| return data |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This (i.e., overloading the model serialization) is the only way I found so far to produce an output like
kind: Line
line:
- drift1:
kind: Drift
length: 0.25
- quad1:
MagneticMultipoleP:
Bn1: 1.0
kind: Quadrupole
length: 1.0
- drift2:
kind: Drift
length: 0.5
- quad2:
MagneticMultipoleP:
Bn1: -1.0
kind: Quadrupole
length: 1.0
- drift3:
kind: Drift
length: 0.5instead of
kind: Line
line:
- drift1:
kind: Drift
length: 0.25
name: drift1
- quad1:
MagneticMultipoleP:
Bn1: 1.0
kind: Quadrupole
length: 1.0
name: quad1
- drift2:
kind: Drift
length: 0.5
name: drift2
- quad2:
MagneticMultipoleP:
Bn1: -1.0
kind: Quadrupole
length: 1.0
name: quad2
- drift3:
kind: Drift
length: 0.5
name: drift3with the name attributes printed out as well (hence repeated).
Do you see other ways to obtain this, other than overloading the model serialization?
I guess we would have to do something similar for the deserialization (through @model_validator(mode="before")?), although I have not been able to make that work just yet.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that the custom deserialization is necessary if we expect that this
yaml_data = yaml.dump(line.model_dump(), default_flow_style=False)
loaded_line = Line(**yaml_data)should lead to line and loaded_line being identical (which we currently assert in the tests and examples).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Possible alternative posted in #14 that does keep the API user-friendly :)
Overwrite validation and model dump. Alternate implementation of #13 that does not make the Python API harder to use. --------- Co-authored-by: Edoardo Zoni <ezoni@lbl.gov>
|
Replaced by #14 :) |
This is an implementation of the suggestion made in #12 (comment).