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

json_encoders inheritance #2024

Closed
art049 opened this issue Oct 22, 2020 · 0 comments · Fixed by #2064
Closed

json_encoders inheritance #2024

art049 opened this issue Oct 22, 2020 · 0 comments · Fixed by #2064

Comments

@art049
Copy link
Contributor

art049 commented Oct 22, 2020

Feature Request

Currently, defining json_encoders in child classes completely overrides the one defined from the parent classes:

from datetime import datetime, timedelta
from pydantic import BaseModel

class A(BaseModel):
    dt: datetime = datetime.now()
    class Config:
        json_encoders = {datetime: lambda _: "encoded_from_A"}

print(A().json())
#> {"dt": "encoded_from_A"}
class B(A):
    timedt: timedelta = timedelta(hours=100)
    class Config:
        json_encoders = {timedelta: lambda _: "encoded_from_B"}

print(B().json())
#> {"dt": "2020-10-23T01:11:20.613624", "timedt": "encoded_from_B"}

I think it would be handy to merge the JSON encoders with the one defined in the parent ones, thus the result would be:

print(B().json())
#> {"dt": "encoded_from_A", "timedt": "encoded_from_B"}

As an extension, it should still be possible to override the parent ones:

class Bbis(A):
    timedt: timedelta = timedelta(hours=100)

    class Config:
        json_encoders = {
            datetime: lambda _: "encoded_from_Bbis",
            timedelta: lambda _: "encoded_from_Bbis",
        }

print(Bbis().json()) 
#> {"dt": "encoded_from_Bbis", "timedt": "encoded_from_Bbis"}

I'm eager to implement this feature if you think it's worth it 😄

@art049 art049 changed the title json_encoders inheritance json_encoders inheritance Oct 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant