Skip to content

Commit e48c9c3

Browse files
authored
TYP: more return annotations for io/* (#47524)
* TYP: more return annotations for io/* * import future
1 parent 2fc7fab commit e48c9c3

File tree

10 files changed

+92
-54
lines changed

10 files changed

+92
-54
lines changed

pandas/io/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -925,7 +925,7 @@ class _BufferedWriter(BytesIO, ABC): # type: ignore[misc]
925925
"""
926926

927927
@abstractmethod
928-
def write_to_buffer(self):
928+
def write_to_buffer(self) -> None:
929929
...
930930

931931
def close(self) -> None:

pandas/io/date_converters.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
"""This module is designed for community supported date conversion functions"""
2+
from __future__ import annotations
3+
24
import warnings
35

46
import numpy as np
57

68
from pandas._libs.tslibs import parsing
9+
from pandas._typing import npt
710
from pandas.util._exceptions import find_stack_level
811

912

10-
def parse_date_time(date_col, time_col):
13+
def parse_date_time(date_col, time_col) -> npt.NDArray[np.object_]:
1114
"""
1215
Parse columns with dates and times into a single datetime column.
1316
@@ -26,7 +29,7 @@ def parse_date_time(date_col, time_col):
2629
return parsing.try_parse_date_and_time(date_col, time_col)
2730

2831

29-
def parse_date_fields(year_col, month_col, day_col):
32+
def parse_date_fields(year_col, month_col, day_col) -> npt.NDArray[np.object_]:
3033
"""
3134
Parse columns with years, months and days into a single date column.
3235
@@ -48,7 +51,9 @@ def parse_date_fields(year_col, month_col, day_col):
4851
return parsing.try_parse_year_month_day(year_col, month_col, day_col)
4952

5053

51-
def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col, second_col):
54+
def parse_all_fields(
55+
year_col, month_col, day_col, hour_col, minute_col, second_col
56+
) -> npt.NDArray[np.object_]:
5257
"""
5358
Parse columns with datetime information into a single datetime column.
5459
@@ -78,7 +83,7 @@ def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col, second_
7883
)
7984

8085

81-
def generic_parser(parse_func, *cols):
86+
def generic_parser(parse_func, *cols) -> np.ndarray:
8287
"""
8388
Use dateparser to parse columns with data information into a single datetime column.
8489

pandas/io/excel/_base.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,7 +1069,7 @@ class ExcelWriter(metaclass=abc.ABCMeta):
10691069
_supported_extensions: tuple[str, ...]
10701070

10711071
def __new__(
1072-
cls,
1072+
cls: type[ExcelWriter],
10731073
path: FilePath | WriteExcelBuffer | ExcelWriter,
10741074
engine: str | None = None,
10751075
date_format: str | None = None,
@@ -1079,7 +1079,7 @@ def __new__(
10791079
if_sheet_exists: Literal["error", "new", "replace", "overlay"] | None = None,
10801080
engine_kwargs: dict | None = None,
10811081
**kwargs,
1082-
):
1082+
) -> ExcelWriter:
10831083
if kwargs:
10841084
if engine_kwargs is not None:
10851085
raise ValueError("Cannot use both engine_kwargs and **kwargs")
@@ -1325,7 +1325,7 @@ def cur_sheet(self):
13251325
return self._cur_sheet
13261326

13271327
@property
1328-
def handles(self):
1328+
def handles(self) -> IOHandles[bytes]:
13291329
"""
13301330
Handles to Excel sheets.
13311331
@@ -1344,7 +1344,7 @@ def path(self):
13441344
self._deprecate("path")
13451345
return self._path
13461346

1347-
def __fspath__(self):
1347+
def __fspath__(self) -> str:
13481348
return getattr(self._handles.handle, "name", "")
13491349

13501350
def _get_sheet_name(self, sheet_name: str | None) -> str:
@@ -1402,10 +1402,10 @@ def check_extension(cls, ext: str) -> Literal[True]:
14021402
return True
14031403

14041404
# Allow use as a contextmanager
1405-
def __enter__(self):
1405+
def __enter__(self) -> ExcelWriter:
14061406
return self
14071407

1408-
def __exit__(self, exc_type, exc_value, traceback):
1408+
def __exit__(self, exc_type, exc_value, traceback) -> None:
14091409
self.close()
14101410

14111411
def close(self) -> None:
@@ -1699,13 +1699,13 @@ def close(self) -> None:
16991699
"""close io if necessary"""
17001700
self._reader.close()
17011701

1702-
def __enter__(self):
1702+
def __enter__(self) -> ExcelFile:
17031703
return self
17041704

1705-
def __exit__(self, exc_type, exc_value, traceback):
1705+
def __exit__(self, exc_type, exc_value, traceback) -> None:
17061706
self.close()
17071707

1708-
def __del__(self):
1708+
def __del__(self) -> None:
17091709
# Ensure we don't leak file descriptors, but put in try/except in case
17101710
# attributes are already deleted
17111711
try:

pandas/io/excel/_openpyxl.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
if TYPE_CHECKING:
3535
from openpyxl.descriptors.serialisable import Serialisable
36+
from openpyxl.workbook import Workbook
3637

3738

3839
class OpenpyxlWriter(ExcelWriter):
@@ -79,7 +80,7 @@ def __init__(
7980
self.book.remove(self.book.worksheets[0])
8081

8182
@property
82-
def book(self):
83+
def book(self) -> Workbook:
8384
"""
8485
Book instance of class openpyxl.workbook.Workbook.
8586

pandas/io/feather_format.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def to_feather(
3131
path: FilePath | WriteBuffer[bytes],
3232
storage_options: StorageOptions = None,
3333
**kwargs,
34-
):
34+
) -> None:
3535
"""
3636
Write a DataFrame to the binary Feather format.
3737

pandas/io/parsers/base_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,7 @@ def _validate_parse_dates_presence(self, columns: Sequence[Hashable]) -> Iterabl
220220
for col in cols_needed
221221
]
222222

223-
def close(self):
223+
def close(self) -> None:
224224
pass
225225

226226
@final

pandas/io/parsers/python_parser.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,11 @@ def _exclude_implicit_index(
308308
}, names
309309

310310
# legacy
311-
def get_chunk(self, size=None):
311+
def get_chunk(
312+
self, size: int | None = None
313+
) -> tuple[
314+
Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
315+
]:
312316
if size is None:
313317
# error: "PythonParser" has no attribute "chunksize"
314318
size = self.chunksize # type: ignore[attr-defined]

pandas/io/parsers/readers.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,22 @@ class _DeprecationConfig(NamedTuple):
493493
}
494494

495495

496-
def validate_integer(name, val, min_val=0):
496+
@overload
497+
def validate_integer(name, val: None, min_val=...) -> None:
498+
...
499+
500+
501+
@overload
502+
def validate_integer(name, val: int | float, min_val=...) -> int:
503+
...
504+
505+
506+
@overload
507+
def validate_integer(name, val: int | None, min_val=...) -> int | None:
508+
...
509+
510+
511+
def validate_integer(name, val: int | float | None, min_val=0) -> int | None:
497512
"""
498513
Checks whether the 'name' parameter for parsing is either
499514
an integer OR float that can SAFELY be cast to an integer
@@ -509,17 +524,18 @@ def validate_integer(name, val, min_val=0):
509524
min_val : int
510525
Minimum allowed value (val < min_val will result in a ValueError)
511526
"""
512-
msg = f"'{name:s}' must be an integer >={min_val:d}"
527+
if val is None:
528+
return val
513529

514-
if val is not None:
515-
if is_float(val):
516-
if int(val) != val:
517-
raise ValueError(msg)
518-
val = int(val)
519-
elif not (is_integer(val) and val >= min_val):
530+
msg = f"'{name:s}' must be an integer >={min_val:d}"
531+
if is_float(val):
532+
if int(val) != val:
520533
raise ValueError(msg)
534+
val = int(val)
535+
elif not (is_integer(val) and val >= min_val):
536+
raise ValueError(msg)
521537

522-
return val
538+
return int(val)
523539

524540

525541
def _validate_names(names: Sequence[Hashable] | None) -> None:
@@ -1784,7 +1800,7 @@ def __exit__(self, exc_type, exc_value, traceback) -> None:
17841800
self.close()
17851801

17861802

1787-
def TextParser(*args, **kwds):
1803+
def TextParser(*args, **kwds) -> TextFileReader:
17881804
"""
17891805
Converts lists of lists/tuples into DataFrames with proper type inference
17901806
and optional (e.g. string to datetime) conversion. Also enables iterating

pandas/io/sas/sas_xport.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ def _read_header(self):
396396
dtype = np.dtype(dtypel)
397397
self._dtype = dtype
398398

399-
def __next__(self):
399+
def __next__(self) -> pd.DataFrame:
400400
return self.read(nrows=self._chunksize or 1)
401401

402402
def _record_count(self) -> int:
@@ -434,7 +434,7 @@ def _record_count(self) -> int:
434434

435435
return (total_records_length - tail_pad) // self.record_length
436436

437-
def get_chunk(self, size=None):
437+
def get_chunk(self, size=None) -> pd.DataFrame:
438438
"""
439439
Reads lines from Xport file and returns as dataframe
440440

0 commit comments

Comments
 (0)