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

exclude_none does not exclude_none on non-pydantic models #1091

Open
matt-mercer opened this issue Nov 22, 2023 · 2 comments
Open

exclude_none does not exclude_none on non-pydantic models #1091

matt-mercer opened this issue Nov 22, 2023 · 2 comments
Assignees

Comments

@matt-mercer
Copy link

to_jsonable_python only seems to apply exclude_none for pydantic models, presumbly for dataclass.dataclass or dict types it is just returning asdict or the supplied value for the top level

Expected

exclude_none=True should be honoured for all dict members in result of to_jsonable_python ..
.... I feel that the behaviour should be homogeneous here, since to_jsonable_python is accepting ( and serialising ) none pydantic types, the fact that this top level instruction is ignored, while others are honoured, seems inconsistent.

Test Case


@pydantic.dataclasses.dataclass
class PDCNoneableModel:
    status_code: int = 200
    test1: str = "ok"
    test2: str | None = None

@dataclasses.dataclass
class DataclassNoneable:
    status_code: int = 200
    test1: str = "ok"
    test2: str | None = None

@pytest.mark.parametrize("modellike", [
    PDCNoneableModel(), DataclassNoneable(), {"test1": "ok", "test2": None}
])
async def test_jsonable_exclude_none(modellike: PDCNoneableModel | DataclassNoneable | dict):

    raw_out = to_jsonable_python(modellike, exclude_none=True)

    assert isinstance(raw_out, dict)
    assert raw_out["status_code"] == 200
    assert "test1" in raw_out
    assert "test2" not in raw_out
@matsjoyce-refeyn
Copy link

A workaround is to use pydantic.TypeAdapter.dump_*, for which the exclude_none flag does seem to work.

@davidhewitt
Copy link
Contributor

Still reproduces on latest main.

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

No branches or pull requests

4 participants