Skip to content

Jsonable encoder stores state which affects encoding across the entire app #1236

@maitham

Description

@maitham

Is there a way to json encode a pydantic model without mutating the underlying config for the object? It seems that if I call jsonable_encoder with a custom encoding it mutates the json encoder config for all models that inherit from API model.


class APIModel(BaseModel):
    class Config(BaseConfig):
        orm_mode = False

    def dump_obj(self, **jsonable_encoder_kwargs: Any) -> Dict[str, Any]:
        return jsonable_encoder(self, **jsonable_encoder_kwargs)

class AccountCreate(APIModel):
    name: str
    type: AccountTypes
    provider: Providers
    balance: Optional[float]
    iso_currency_code: Optional[str]
    logo: str
    provider_metadata: ProviderMetadata
    account_metadata: AccountMetadata


acc = jsonable_encoder(account, custom_encoder={datetime: lambda x: x})
parsed_account = AccountCreate({**acc, "id": result.id}) # when this is dumped the new object will still use custom encoder defined in the previous step. 

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions