Skip to content

Commit d7a203d

Browse files
twoertweinmroeschke
authored andcommitted
TYP: fix a few types (pandas-dev#54976)
* TYP: fix a few types * namespace test * read_fwf overloads * Revert "namespace test" This reverts commit 0f72079. * revert util and move kwds * isort
1 parent 0deadef commit d7a203d

File tree

6 files changed

+86
-34
lines changed

6 files changed

+86
-34
lines changed

pandas/core/frame.py

+16-8
Original file line numberDiff line numberDiff line change
@@ -1926,11 +1926,17 @@ def to_dict(
19261926
self,
19271927
orient: Literal["dict", "list", "series", "split", "tight", "index"] = ...,
19281928
into: type[dict] = ...,
1929+
index: bool = ...,
19291930
) -> dict:
19301931
...
19311932

19321933
@overload
1933-
def to_dict(self, orient: Literal["records"], into: type[dict] = ...) -> list[dict]:
1934+
def to_dict(
1935+
self,
1936+
orient: Literal["records"],
1937+
into: type[dict] = ...,
1938+
index: bool = ...,
1939+
) -> list[dict]:
19341940
...
19351941

19361942
@deprecate_nonkeyword_arguments(
@@ -11297,7 +11303,7 @@ def _reduce_axis1(self, name: str, func, skipna: bool) -> Series:
1129711303
def any( # type: ignore[override]
1129811304
self,
1129911305
*,
11300-
axis: Axis = 0,
11306+
axis: Axis | None = 0,
1130111307
bool_only: bool = False,
1130211308
skipna: bool = True,
1130311309
**kwargs,
@@ -11312,7 +11318,7 @@ def any( # type: ignore[override]
1131211318
@doc(make_doc("all", ndim=2))
1131311319
def all(
1131411320
self,
11315-
axis: Axis = 0,
11321+
axis: Axis | None = 0,
1131611322
bool_only: bool = False,
1131711323
skipna: bool = True,
1131811324
**kwargs,
@@ -11711,6 +11717,7 @@ def quantile(
1171111717
axis: Axis = ...,
1171211718
numeric_only: bool = ...,
1171311719
interpolation: QuantileInterpolation = ...,
11720+
method: Literal["single", "table"] = ...,
1171411721
) -> Series:
1171511722
...
1171611723

@@ -11721,6 +11728,7 @@ def quantile(
1172111728
axis: Axis = ...,
1172211729
numeric_only: bool = ...,
1172311730
interpolation: QuantileInterpolation = ...,
11731+
method: Literal["single", "table"] = ...,
1172411732
) -> Series | DataFrame:
1172511733
...
1172611734

@@ -11731,6 +11739,7 @@ def quantile(
1173111739
axis: Axis = ...,
1173211740
numeric_only: bool = ...,
1173311741
interpolation: QuantileInterpolation = ...,
11742+
method: Literal["single", "table"] = ...,
1173411743
) -> Series | DataFrame:
1173511744
...
1173611745

@@ -11830,11 +11839,10 @@ def quantile(
1183011839

1183111840
if not is_list_like(q):
1183211841
# BlockManager.quantile expects listlike, so we wrap and unwrap here
11833-
# error: List item 0 has incompatible type "Union[float, Union[Union[
11834-
# ExtensionArray, ndarray[Any, Any]], Index, Series], Sequence[float]]";
11835-
# expected "float"
11836-
res_df = self.quantile( # type: ignore[call-overload]
11837-
[q],
11842+
# error: List item 0 has incompatible type "float | ExtensionArray |
11843+
# ndarray[Any, Any] | Index | Series | Sequence[float]"; expected "float"
11844+
res_df = self.quantile(
11845+
[q], # type: ignore[list-item]
1183811846
axis=axis,
1183911847
numeric_only=numeric_only,
1184011848
interpolation=interpolation,

pandas/core/generic.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -11827,7 +11827,7 @@ def _logical_func(
1182711827
self,
1182811828
name: str,
1182911829
func,
11830-
axis: Axis = 0,
11830+
axis: Axis | None = 0,
1183111831
bool_only: bool_t = False,
1183211832
skipna: bool_t = True,
1183311833
**kwargs,
@@ -11840,7 +11840,10 @@ def _logical_func(
1184011840
res = self._logical_func(
1184111841
name, func, axis=0, bool_only=bool_only, skipna=skipna, **kwargs
1184211842
)
11843-
return res._logical_func(name, func, skipna=skipna, **kwargs)
11843+
# error: Item "bool" of "Series | bool" has no attribute "_logical_func"
11844+
return res._logical_func( # type: ignore[union-attr]
11845+
name, func, skipna=skipna, **kwargs
11846+
)
1184411847
elif axis is None:
1184511848
axis = 0
1184611849

pandas/io/excel/_base.py

+12-19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from __future__ import annotations
22

3-
import abc
43
from collections.abc import (
54
Hashable,
65
Iterable,
@@ -549,7 +548,7 @@ def read_excel(
549548
_WorkbookT = TypeVar("_WorkbookT")
550549

551550

552-
class BaseExcelReader(Generic[_WorkbookT], metaclass=abc.ABCMeta):
551+
class BaseExcelReader(Generic[_WorkbookT]):
553552
book: _WorkbookT
554553

555554
def __init__(
@@ -589,13 +588,11 @@ def __init__(
589588
)
590589

591590
@property
592-
@abc.abstractmethod
593591
def _workbook_class(self) -> type[_WorkbookT]:
594-
pass
592+
raise NotImplementedError
595593

596-
@abc.abstractmethod
597594
def load_workbook(self, filepath_or_buffer, engine_kwargs) -> _WorkbookT:
598-
pass
595+
raise NotImplementedError
599596

600597
def close(self) -> None:
601598
if hasattr(self, "book"):
@@ -611,21 +608,17 @@ def close(self) -> None:
611608
self.handles.close()
612609

613610
@property
614-
@abc.abstractmethod
615611
def sheet_names(self) -> list[str]:
616-
pass
612+
raise NotImplementedError
617613

618-
@abc.abstractmethod
619614
def get_sheet_by_name(self, name: str):
620-
pass
615+
raise NotImplementedError
621616

622-
@abc.abstractmethod
623617
def get_sheet_by_index(self, index: int):
624-
pass
618+
raise NotImplementedError
625619

626-
@abc.abstractmethod
627620
def get_sheet_data(self, sheet, rows: int | None = None):
628-
pass
621+
raise NotImplementedError
629622

630623
def raise_if_bad_sheet_by_index(self, index: int) -> None:
631624
n_sheets = len(self.sheet_names)
@@ -940,7 +933,7 @@ def parse(
940933

941934

942935
@doc(storage_options=_shared_docs["storage_options"])
943-
class ExcelWriter(Generic[_WorkbookT], metaclass=abc.ABCMeta):
936+
class ExcelWriter(Generic[_WorkbookT]):
944937
"""
945938
Class for writing DataFrame objects into excel sheets.
946939
@@ -1178,20 +1171,19 @@ def engine(self) -> str:
11781171
return self._engine
11791172

11801173
@property
1181-
@abc.abstractmethod
11821174
def sheets(self) -> dict[str, Any]:
11831175
"""Mapping of sheet names to sheet objects."""
1176+
raise NotImplementedError
11841177

11851178
@property
1186-
@abc.abstractmethod
11871179
def book(self) -> _WorkbookT:
11881180
"""
11891181
Book instance. Class type will depend on the engine used.
11901182
11911183
This attribute can be used to access engine-specific features.
11921184
"""
1185+
raise NotImplementedError
11931186

1194-
@abc.abstractmethod
11951187
def _write_cells(
11961188
self,
11971189
cells,
@@ -1214,12 +1206,13 @@ def _write_cells(
12141206
freeze_panes: int tuple of length 2
12151207
contains the bottom-most row and right-most column to freeze
12161208
"""
1209+
raise NotImplementedError
12171210

1218-
@abc.abstractmethod
12191211
def _save(self) -> None:
12201212
"""
12211213
Save workbook to disk.
12221214
"""
1215+
raise NotImplementedError
12231216

12241217
def __init__(
12251218
self,

pandas/io/formats/excel.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -941,9 +941,7 @@ def write(
941941
if isinstance(writer, ExcelWriter):
942942
need_save = False
943943
else:
944-
# error: Cannot instantiate abstract class 'ExcelWriter' with abstract
945-
# attributes 'engine', 'save', 'supported_extensions' and 'write_cells'
946-
writer = ExcelWriter( # type: ignore[abstract]
944+
writer = ExcelWriter(
947945
writer,
948946
engine=engine,
949947
storage_options=storage_options,

pandas/io/json/_json.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@
8282
JSONEngine,
8383
JSONSerializable,
8484
ReadBuffer,
85+
Self,
8586
StorageOptions,
8687
WriteBuffer,
8788
)
@@ -1056,7 +1057,7 @@ def close(self) -> None:
10561057
if self.handles is not None:
10571058
self.handles.close()
10581059

1059-
def __iter__(self: JsonReader[FrameSeriesStrT]) -> JsonReader[FrameSeriesStrT]:
1060+
def __iter__(self) -> Self:
10601061
return self
10611062

10621063
@overload
@@ -1099,7 +1100,7 @@ def __next__(self) -> DataFrame | Series:
10991100
else:
11001101
return obj
11011102

1102-
def __enter__(self) -> JsonReader[FrameSeriesStrT]:
1103+
def __enter__(self) -> Self:
11031104
return self
11041105

11051106
def __exit__(

pandas/io/parsers/readers.py

+49
Original file line numberDiff line numberDiff line change
@@ -1307,13 +1307,60 @@ def read_table(
13071307
return _read(filepath_or_buffer, kwds)
13081308

13091309

1310+
@overload
1311+
def read_fwf(
1312+
filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
1313+
*,
1314+
colspecs: Sequence[tuple[int, int]] | str | None = ...,
1315+
widths: Sequence[int] | None = ...,
1316+
infer_nrows: int = ...,
1317+
dtype_backend: DtypeBackend | lib.NoDefault = ...,
1318+
iterator: Literal[True],
1319+
chunksize: int | None = ...,
1320+
**kwds,
1321+
) -> TextFileReader:
1322+
...
1323+
1324+
1325+
@overload
1326+
def read_fwf(
1327+
filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
1328+
*,
1329+
colspecs: Sequence[tuple[int, int]] | str | None = ...,
1330+
widths: Sequence[int] | None = ...,
1331+
infer_nrows: int = ...,
1332+
dtype_backend: DtypeBackend | lib.NoDefault = ...,
1333+
iterator: bool = ...,
1334+
chunksize: int,
1335+
**kwds,
1336+
) -> TextFileReader:
1337+
...
1338+
1339+
1340+
@overload
1341+
def read_fwf(
1342+
filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
1343+
*,
1344+
colspecs: Sequence[tuple[int, int]] | str | None = ...,
1345+
widths: Sequence[int] | None = ...,
1346+
infer_nrows: int = ...,
1347+
dtype_backend: DtypeBackend | lib.NoDefault = ...,
1348+
iterator: Literal[False] = ...,
1349+
chunksize: None = ...,
1350+
**kwds,
1351+
) -> DataFrame:
1352+
...
1353+
1354+
13101355
def read_fwf(
13111356
filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str],
13121357
*,
13131358
colspecs: Sequence[tuple[int, int]] | str | None = "infer",
13141359
widths: Sequence[int] | None = None,
13151360
infer_nrows: int = 100,
13161361
dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
1362+
iterator: bool = False,
1363+
chunksize: int | None = None,
13171364
**kwds,
13181365
) -> DataFrame | TextFileReader:
13191366
r"""
@@ -1412,6 +1459,8 @@ def read_fwf(
14121459
kwds["colspecs"] = colspecs
14131460
kwds["infer_nrows"] = infer_nrows
14141461
kwds["engine"] = "python-fwf"
1462+
kwds["iterator"] = iterator
1463+
kwds["chunksize"] = chunksize
14151464

14161465
check_dtype_backend(dtype_backend)
14171466
kwds["dtype_backend"] = dtype_backend

0 commit comments

Comments
 (0)