Skip to content
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

Open
lidatong opened this issue Nov 4, 2018 · 6 comments
Open

API features / improvements #31

lidatong opened this issue Nov 4, 2018 · 6 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@lidatong
Copy link
Owner

lidatong commented Nov 4, 2018

Creating this parent issue to track API improvements / upgrades

  1. Support forward references (which will enable recursive dataclasses): Hacky workaround for forward references #5
  2. Full typing support: "Type[xxx]" has no attribute "from_json" #23
  3. coerce_keys kwarg for encoding: coerce_keys option #29
  4. user-supplied overrides user-supplied overrides #42
  5. Sharing encoder / decoder in wider scopes (currently must be per-field. type, class, global are all potential scopes) wider config scopes #139
@baco
Copy link

baco commented Mar 22, 2020

What's the ETA for fixing this?

@Trolldemorted
Copy link

Is there anything we can do as a workaround to make mypy pass?

@huyz
Copy link

huyz commented Dec 1, 2021

Is there anything we can do as a workaround to make mypy pass?

Besides # type: ignore?

@gshpychka
Copy link

@lidatong It is possible to have to_json include computed properties (@property)? I'm using the package for a json repr, not purely for serialization/deserialization.

@USSX-Hares
Copy link
Collaborator

@gshpychka, you can try the following:

  1. Define the DataClassJsonMixin-nested class A
  2. Define class B which is not dataclass on its own
  3. In class B, define the required property

Code Example

from 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

{"field_1": "1234", "field_2": 0}
{"field_1": "456", "field_2": 3}

@thewizardplusplus
Copy link

thewizardplusplus commented Oct 27, 2022

@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:

{"field_1": "12345", "field_2": 5}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

7 participants