From 449eb46a44096e3454c3cd4905a4d14e9f7ddf69 Mon Sep 17 00:00:00 2001 From: James Spencer Date: Wed, 13 Sep 2023 22:06:29 +0100 Subject: [PATCH] Correct type annotation for to_dict. The `into` argument of DataFrame.to_dict and Series.to_dict can be either a class or instance of a class of dict; this is covariant - subclasses of dict can also be used. The argument was annotated as `type[dict]` though, so type checkers marked passing initialized objects (required for collections.defaultdict) as an incorrect argument type. Fix by annotating `into` to take either a subclass of dict or an initialized instance of a subclass of dict. --- pandas/core/frame.py | 6 +++--- pandas/core/methods/to_dict.py | 2 +- pandas/core/series.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8fcb91c846826..f2497f7c6eaf7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1925,7 +1925,7 @@ def _create_data_for_split_and_tight_to_dict( def to_dict( self, orient: Literal["dict", "list", "series", "split", "tight", "index"] = ..., - into: type[dict] = ..., + into: type[dict] | dict = ..., index: bool = ..., ) -> dict: ... @@ -1934,7 +1934,7 @@ def to_dict( def to_dict( self, orient: Literal["records"], - into: type[dict] = ..., + into: type[dict] | dict = ..., index: bool = ..., ) -> list[dict]: ... @@ -1947,7 +1947,7 @@ def to_dict( orient: Literal[ "dict", "list", "series", "split", "tight", "records", "index" ] = "dict", - into: type[dict] = dict, + into: type[dict] | dict = dict, index: bool = True, ) -> dict | list[dict]: """ diff --git a/pandas/core/methods/to_dict.py b/pandas/core/methods/to_dict.py index f4e0dcddcd34a..c6ab28fbacbb3 100644 --- a/pandas/core/methods/to_dict.py +++ b/pandas/core/methods/to_dict.py @@ -24,7 +24,7 @@ def to_dict( orient: Literal[ "dict", "list", "series", "split", "tight", "records", "index" ] = "dict", - into: type[dict] = dict, + into: type[dict] | dict = dict, index: bool = True, ) -> dict | list[dict]: """ diff --git a/pandas/core/series.py b/pandas/core/series.py index 9b5c8829fd5ff..ed9247a5a926e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1926,7 +1926,7 @@ def keys(self) -> Index: """ return self.index - def to_dict(self, into: type[dict] = dict) -> dict: + def to_dict(self, into: type[dict] | dict = dict) -> dict: """ Convert Series to {label -> value} dict or dict-like object.