-
Notifications
You must be signed in to change notification settings - Fork 80
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
Question: computed fields #573
Comments
Maybe we can just use @Property decorator? Like this: class MyModel(msgspec.Struct):
field1: int
field2: int
@property
def fieldSum(self) -> int:
return self.field1 + self.field2 But it is caculated when we access it. |
The goal is to have this field in encoded json, and in the result of |
I guess the cleanest way to do that, would be to hand that computed field on instantiating the class. Seems a bit out of scope. |
For now, try:
Until #199 is done, you could use |
Apologies for the delay here
By this do you mean "computed fields" that will be part of the encoded representation, but aren't/can't-be used for decoding? Something like: class Ex(Struct):
a: int
@msgspec.computed_field
def b(self):
return self.a + 1
obj = Ex(1)
print(f"b = {obj.b}")
#> b = 2
msg = msgspec.json.encode(obj)
print(msg)
#> b'{"a":1,"b":2}'
obj2 = msgspec.json.decode(b'{"a":1}',` type=Ex) # b is not needed (or used) for decoding
assert obj == obj2 This functionality doesn't currently exist in
class Test(msgspec.Struct, forbid_unknown_fields=True):
a: int
@msgspec.computed_field
def b(self):
return self.a + 1
msg = b'{"a": 1, "b": 2}'
msgspec.json.decode(msg, type=Test) # does this error since `b` isn't a true field? |
@jcrist, thank you for your reply.
Naming isn't my strongest suit :), but I think the
It definitely should raise an error for the sake of specification consistency. Another question is how to behave when
|
It should be noted that there are use cases for computed fields that are encoded (above), and computed fields that aren't (recursive or cyclic data structures like OpenAPI) |
Description
Sorry if I missed this in the docs or other issues but is there a more decent way to create a computed field based on the value of another field/s?
Currently my implementation looks a bit clumsy:
in dataclass fields we have
init=False
option but not in msgstruct.fieldThe text was updated successfully, but these errors were encountered: