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

Add support for str subclasses #348

Closed
rpmcginty opened this issue Apr 4, 2022 · 2 comments
Closed

Add support for str subclasses #348

rpmcginty opened this issue Apr 4, 2022 · 2 comments
Labels

Comments

@rpmcginty
Copy link
Contributor

Problem

as of v0.5.7, any subclassed str classes are instantiated using the default str class.

Example

class MyString(str):
    ...
    def my_useless_odd_number_detector(self) -> bool:
        return len(self) % 2 != 0

@dataclass_json
@dataclass
class MyDC:
    my_str: MyString

    def __post_init__(self):
        print(f"IS it odd? -> {self.my_str.my_useless_odd_number_detector()}")

# Error!
MyDC.from_dict(dict(my_str="123"))

To work around this, you must override the decoder. But this must be done in every dataclass that references that type. Alternatively, we can add this decoder to the global config. but this can be cumbersome if you are subclassing str many times.

For context, I have a subclassed str into ValidatedStr which provides validation (regex, length constraints) against the string. I vend this ValidatedStr class for usage across other packages. I do not want to require others using this subclass to have to explicitly specify the decoder every time or update a global config.

Feature Request

Modify the decode_dataclass logic to further distinguish between custom subclassed str classes.

@george-zubrienko
Copy link
Collaborator

I think you should use composition instead of inheritance for this use case - would make life much easier. As for the library behaviour, I agree this code should not raise

@matt035343
Copy link
Collaborator

matt035343 commented Aug 12, 2023

This seems to be fixed as of version 0.5.9 (PR #375). Please reopen if the issue persists.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants