From cfdb9476d4e863f722f5c23f792caf7566eccafd Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sat, 30 Nov 2024 09:06:18 -0500 Subject: [PATCH] Refine dataclass check Change the `dataclasses.is_dataclass` overload used from ``` @overload def is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... ``` to ``` @overload def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ... ``` This fixes the following mypy errors: ``` fastapi/encoders.py:244: error: Argument 1 to "asdict" has incompatible type "DataclassInstance | type[DataclassInstance]"; expected "DataclassInstance" [arg-type] fastapi/routing.py:122: error: Argument 1 to "asdict" has incompatible type "DataclassInstance | type[DataclassInstance]"; expected "DataclassInstance" [arg-type] Found 2 errors in 2 files (checked 44 source files) ``` --- fastapi/encoders.py | 2 +- fastapi/routing.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 451ea0760..c416abbcb 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -240,7 +240,7 @@ def jsonable_encoder( custom_encoder=encoders, sqlalchemy_safe=sqlalchemy_safe, ) - if dataclasses.is_dataclass(obj): + if dataclasses.is_dataclass(type(obj)): obj_dict = dataclasses.asdict(obj) return jsonable_encoder( obj_dict, diff --git a/fastapi/routing.py b/fastapi/routing.py index 8ea4bb219..c0d9c821a 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -118,7 +118,7 @@ def _prepare_response_content( ) for k, v in res.items() } - elif dataclasses.is_dataclass(res): + elif dataclasses.is_dataclass(type(res)): return dataclasses.asdict(res) return res