Skip to content

Commit

Permalink
Correct type annotation for DataFrame.to_dict.
Browse files Browse the repository at this point in the history
The `into` argument of DataFrame.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.
  • Loading branch information
jsspencer committed Sep 13, 2023
1 parent 4e28925 commit afbc799
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
6 changes: 3 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
...
Expand All @@ -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]:
...
Expand All @@ -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]:
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/methods/to_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
"""
Expand Down

0 comments on commit afbc799

Please sign in to comment.