Skip to content

Commit 10f31f6

Browse files
authored
Fix some typing errors (#57816)
* Fix some typing errors * Review * Reuse types * Reuse types * Reuse types * Add error message * Add error message * Revert "Reuse types" This reverts commit 0e9e7bc. * Revert "Reuse types" This reverts commit 0fcb8cd. * Revert "Reuse types" This reverts commit 89dec50. * Remove comment * Add error message
1 parent b150258 commit 10f31f6

File tree

9 files changed

+52
-33
lines changed

9 files changed

+52
-33
lines changed

pandas/core/methods/selectn.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def compute(self, method: str) -> DataFrame:
213213
f"cannot use method {method!r} with this dtype"
214214
)
215215

216-
def get_indexer(current_indexer, other_indexer):
216+
def get_indexer(current_indexer: Index, other_indexer: Index) -> Index:
217217
"""
218218
Helper function to concat `current_indexer` and `other_indexer`
219219
depending on `method`

pandas/core/methods/to_dict.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,8 @@ def to_dict(
155155
stacklevel=find_stack_level(),
156156
)
157157
# GH16122
158-
into_c = com.standardize_mapping(into)
158+
# error: Call to untyped function "standardize_mapping" in typed context
159+
into_c = com.standardize_mapping(into) # type: ignore[no-untyped-call]
159160

160161
# error: Incompatible types in assignment (expression has type "str",
161162
# variable has type "Literal['dict', 'list', 'series', 'split', 'tight',

pandas/core/ops/invalid.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,26 @@
77
import operator
88
from typing import (
99
TYPE_CHECKING,
10+
Any,
1011
Callable,
1112
NoReturn,
1213
)
1314

1415
import numpy as np
1516

1617
if TYPE_CHECKING:
17-
from pandas._typing import npt
18+
from pandas._typing import (
19+
ArrayLike,
20+
Scalar,
21+
npt,
22+
)
1823

1924

20-
def invalid_comparison(left, right, op) -> npt.NDArray[np.bool_]:
25+
def invalid_comparison(
26+
left: ArrayLike,
27+
right: ArrayLike | Scalar,
28+
op: Callable[[Any, Any], bool],
29+
) -> npt.NDArray[np.bool_]:
2130
"""
2231
If a comparison has mismatched types and is not necessarily meaningful,
2332
follow python3 conventions by:
@@ -59,7 +68,7 @@ def make_invalid_op(name: str) -> Callable[..., NoReturn]:
5968
invalid_op : function
6069
"""
6170

62-
def invalid_op(self, other=None) -> NoReturn:
71+
def invalid_op(self: object, other: object = None) -> NoReturn:
6372
typ = type(self).__name__
6473
raise TypeError(f"cannot perform {name} with this index type: {typ}")
6574

pandas/io/common.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ def stringify_path(
278278
return _expand_user(filepath_or_buffer)
279279

280280

281-
def urlopen(*args, **kwargs):
281+
def urlopen(*args: Any, **kwargs: Any) -> Any:
282282
"""
283283
Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of
284284
the stdlib.
@@ -972,7 +972,7 @@ def __init__(
972972
mode: Literal["r", "a", "w", "x"] = "r",
973973
fileobj: ReadBuffer[bytes] | WriteBuffer[bytes] | None = None,
974974
archive_name: str | None = None,
975-
**kwargs,
975+
**kwargs: Any,
976976
) -> None:
977977
super().__init__()
978978
self.archive_name = archive_name
@@ -1025,7 +1025,7 @@ def __init__(
10251025
file: FilePath | ReadBuffer[bytes] | WriteBuffer[bytes],
10261026
mode: str,
10271027
archive_name: str | None = None,
1028-
**kwargs,
1028+
**kwargs: Any,
10291029
) -> None:
10301030
super().__init__()
10311031
mode = mode.replace("b", "")

pandas/io/excel/_odswriter.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
)
1919

2020
if TYPE_CHECKING:
21+
from odf.opendocument import OpenDocumentSpreadsheet
22+
2123
from pandas._typing import (
2224
ExcelWriterIfSheetExists,
2325
FilePath,
@@ -37,12 +39,12 @@ def __init__(
3739
path: FilePath | WriteExcelBuffer | ExcelWriter,
3840
engine: str | None = None,
3941
date_format: str | None = None,
40-
datetime_format=None,
42+
datetime_format: str | None = None,
4143
mode: str = "w",
4244
storage_options: StorageOptions | None = None,
4345
if_sheet_exists: ExcelWriterIfSheetExists | None = None,
4446
engine_kwargs: dict[str, Any] | None = None,
45-
**kwargs,
47+
**kwargs: Any,
4648
) -> None:
4749
from odf.opendocument import OpenDocumentSpreadsheet
4850

@@ -63,7 +65,7 @@ def __init__(
6365
self._style_dict: dict[str, str] = {}
6466

6567
@property
66-
def book(self):
68+
def book(self) -> OpenDocumentSpreadsheet:
6769
"""
6870
Book instance of class odf.opendocument.OpenDocumentSpreadsheet.
6971
@@ -149,7 +151,7 @@ def _write_cells(
149151
for row_nr in range(max(rows.keys()) + 1):
150152
wks.addElement(rows[row_nr])
151153

152-
def _make_table_cell_attributes(self, cell) -> dict[str, int | str]:
154+
def _make_table_cell_attributes(self, cell: ExcelCell) -> dict[str, int | str]:
153155
"""Convert cell attributes to OpenDocument attributes
154156
155157
Parameters
@@ -171,7 +173,7 @@ def _make_table_cell_attributes(self, cell) -> dict[str, int | str]:
171173
attributes["numbercolumnsspanned"] = cell.mergeend
172174
return attributes
173175

174-
def _make_table_cell(self, cell) -> tuple[object, Any]:
176+
def _make_table_cell(self, cell: ExcelCell) -> tuple[object, Any]:
175177
"""Convert cell data to an OpenDocument spreadsheet cell
176178
177179
Parameters

pandas/io/formats/css.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def _side_expander(prop_fmt: str) -> Callable:
3636
function: Return to call when a 'border(-{side}): {value}' string is encountered
3737
"""
3838

39-
def expand(self, prop: str, value: str) -> Generator[tuple[str, str], None, None]:
39+
def expand(
40+
self: CSSResolver, prop: str, value: str
41+
) -> Generator[tuple[str, str], None, None]:
4042
"""
4143
Expand shorthand property into side-specific property (top, right, bottom, left)
4244
@@ -81,7 +83,9 @@ def _border_expander(side: str = "") -> Callable:
8183
if side != "":
8284
side = f"-{side}"
8385

84-
def expand(self, prop: str, value: str) -> Generator[tuple[str, str], None, None]:
86+
def expand(
87+
self: CSSResolver, prop: str, value: str
88+
) -> Generator[tuple[str, str], None, None]:
8589
"""
8690
Expand border into color, style, and width tuples
8791
@@ -343,7 +347,9 @@ def _update_other_units(self, props: dict[str, str]) -> dict[str, str]:
343347
)
344348
return props
345349

346-
def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS) -> str:
350+
def size_to_pt(
351+
self, in_val: str, em_pt: float | None = None, conversions: dict = UNIT_RATIOS
352+
) -> str:
347353
def _error() -> str:
348354
warnings.warn(
349355
f"Unhandled size: {in_val!r}",

pandas/io/formats/printing.py

+17-10
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
)
1212
import sys
1313
from typing import (
14+
TYPE_CHECKING,
1415
Any,
1516
Callable,
1617
TypeVar,
@@ -24,12 +25,14 @@
2425

2526
from pandas.io.formats.console import get_console_size
2627

28+
if TYPE_CHECKING:
29+
from pandas._typing import ListLike
2730
EscapeChars = Union[Mapping[str, str], Iterable[str]]
2831
_KT = TypeVar("_KT")
2932
_VT = TypeVar("_VT")
3033

3134

32-
def adjoin(space: int, *lists: list[str], **kwargs) -> str:
35+
def adjoin(space: int, *lists: list[str], **kwargs: Any) -> str:
3336
"""
3437
Glues together two sets of strings using the amount of space requested.
3538
The idea is to prettify.
@@ -98,7 +101,7 @@ def _adj_justify(texts: Iterable[str], max_len: int, mode: str = "right") -> lis
98101

99102

100103
def _pprint_seq(
101-
seq: Sequence, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds
104+
seq: ListLike, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds: Any
102105
) -> str:
103106
"""
104107
internal. pprinter for iterables. you should probably use pprint_thing()
@@ -136,7 +139,7 @@ def _pprint_seq(
136139

137140

138141
def _pprint_dict(
139-
seq: Mapping, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds
142+
seq: Mapping, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds: Any
140143
) -> str:
141144
"""
142145
internal. pprinter for iterables. you should probably use pprint_thing()
@@ -167,7 +170,7 @@ def _pprint_dict(
167170

168171

169172
def pprint_thing(
170-
thing: Any,
173+
thing: object,
171174
_nest_lvl: int = 0,
172175
escape_chars: EscapeChars | None = None,
173176
default_escapes: bool = False,
@@ -225,7 +228,10 @@ def as_escaped_string(
225228
)
226229
elif is_sequence(thing) and _nest_lvl < get_option("display.pprint_nest_depth"):
227230
result = _pprint_seq(
228-
thing,
231+
# error: Argument 1 to "_pprint_seq" has incompatible type "object";
232+
# expected "ExtensionArray | ndarray[Any, Any] | Index | Series |
233+
# SequenceNotStr[Any] | range"
234+
thing, # type: ignore[arg-type]
229235
_nest_lvl,
230236
escape_chars=escape_chars,
231237
quote_strings=quote_strings,
@@ -240,7 +246,7 @@ def as_escaped_string(
240246

241247

242248
def pprint_thing_encoded(
243-
object, encoding: str = "utf-8", errors: str = "replace"
249+
object: object, encoding: str = "utf-8", errors: str = "replace"
244250
) -> bytes:
245251
value = pprint_thing(object) # get unicode representation of object
246252
return value.encode(encoding, errors)
@@ -252,7 +258,8 @@ def enable_data_resource_formatter(enable: bool) -> None:
252258
return
253259
from IPython import get_ipython
254260

255-
ip = get_ipython()
261+
# error: Call to untyped function "get_ipython" in typed context
262+
ip = get_ipython() # type: ignore[no-untyped-call]
256263
if ip is None:
257264
# still not in IPython
258265
return
@@ -289,7 +296,7 @@ def default_pprint(thing: Any, max_seq_items: int | None = None) -> str:
289296

290297

291298
def format_object_summary(
292-
obj,
299+
obj: ListLike,
293300
formatter: Callable,
294301
is_justify: bool = True,
295302
name: str | None = None,
@@ -525,7 +532,7 @@ def justify(self, texts: Any, max_len: int, mode: str = "right") -> list[str]:
525532
else:
526533
return [x.rjust(max_len) for x in texts]
527534

528-
def adjoin(self, space: int, *lists, **kwargs) -> str:
535+
def adjoin(self, space: int, *lists: Any, **kwargs: Any) -> str:
529536
return adjoin(space, *lists, strlen=self.len, justfunc=self.justify, **kwargs)
530537

531538

@@ -557,7 +564,7 @@ def justify(
557564
self, texts: Iterable[str], max_len: int, mode: str = "right"
558565
) -> list[str]:
559566
# re-calculate padding space per str considering East Asian Width
560-
def _get_pad(t):
567+
def _get_pad(t: str) -> int:
561568
return max_len - self.len(t) + len(t)
562569

563570
if mode == "left":

pandas/plotting/_misc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -672,7 +672,7 @@ def reset(self) -> None:
672672
# error: Cannot access "__init__" directly
673673
self.__init__() # type: ignore[misc]
674674

675-
def _get_canonical_key(self, key):
675+
def _get_canonical_key(self, key: str) -> str:
676676
return self._ALIASES.get(key, key)
677677

678678
@contextmanager

pyproject.toml

-6
Original file line numberDiff line numberDiff line change
@@ -594,10 +594,8 @@ module = [
594594
"pandas.core.interchange.dataframe_protocol", # TODO
595595
"pandas.core.interchange.from_dataframe", # TODO
596596
"pandas.core.internals.*", # TODO
597-
"pandas.core.methods.*", # TODO
598597
"pandas.core.ops.array_ops", # TODO
599598
"pandas.core.ops.common", # TODO
600-
"pandas.core.ops.invalid", # TODO
601599
"pandas.core.ops.missing", # TODO
602600
"pandas.core.reshape.*", # TODO
603601
"pandas.core.strings.*", # TODO
@@ -630,15 +628,12 @@ module = [
630628
"pandas.io.clipboard", # TODO
631629
"pandas.io.excel._base", # TODO
632630
"pandas.io.excel._odfreader", # TODO
633-
"pandas.io.excel._odswriter", # TODO
634631
"pandas.io.excel._openpyxl", # TODO
635632
"pandas.io.excel._pyxlsb", # TODO
636633
"pandas.io.excel._xlrd", # TODO
637634
"pandas.io.excel._xlsxwriter", # TODO
638-
"pandas.io.formats.css", # TODO
639635
"pandas.io.formats.excel", # TODO
640636
"pandas.io.formats.format", # TODO
641-
"pandas.io.formats.printing", # TODO
642637
"pandas.io.formats.style", # TODO
643638
"pandas.io.formats.style_render", # TODO
644639
"pandas.io.formats.xml", # TODO
@@ -647,7 +642,6 @@ module = [
647642
"pandas.io.sas.sas_xport", # TODO
648643
"pandas.io.sas.sas7bdat", # TODO
649644
"pandas.io.clipboards", # TODO
650-
"pandas.io.common", # TODO
651645
"pandas.io.html", # TODO
652646
"pandas.io.parquet", # TODO
653647
"pandas.io.pytables", # TODO

0 commit comments

Comments
 (0)