-
Notifications
You must be signed in to change notification settings - Fork 155
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
API features / improvements #31
Comments
What's the ETA for fixing this? |
Is there anything we can do as a workaround to make mypy pass? |
Besides |
@lidatong It is possible to have |
@gshpychka, you can try the following:
Code Examplefrom dataclasses_json import *
from dataclasses import *
@dataclass
class ClassA(DataClassJsonMixin):
field_1: str
field_2: int = field(init=False, repr=True, default=0)
class ClassB(ClassA):
@property
def field_2(self) -> int:
return len(self.field_1)
def main():
a = ClassA('1234')
b = ClassB('456')
print(a.to_json())
print(b.to_json())
return 0
if (__name__ == '__main__'):
exit_code = main()
exit(exit_code) Execution Result
|
@gshpychka, @USSX-Hares, my solution: import dataclasses
import dataclasses_json
@dataclasses.dataclass
# the solution will only work when using inheritance
class SomeClass(dataclasses_json.DataClassJsonMixin):
field_1: str
@property
def field_2(self) -> int:
return len(self.field_1)
# override the method in order to add computable properties to JSON
def to_dict(
self,
encode_json: bool = False,
) -> dict[str, dataclasses_json.core.Json]:
# first call the parent method to get non-computable properties
data = super().to_dict(encode_json=encode_json)
# then manually set computable properties
data["field_2"] = self.field_2
return data
if __name__ == "__main__":
instance = SomeClass("12345")
print(instance.to_json()) Output:
|
Creating this parent issue to track API improvements / upgrades
coerce_keys
kwarg for encoding: coerce_keys option #29user-supplied overrides user-supplied overrides #42The text was updated successfully, but these errors were encountered: