Skip to content

Commit ef5b45d

Browse files
author
MomIsBestFriend
committed
TYP: Typing annotations
1 parent f0cb545 commit ef5b45d

9 files changed

+102
-92
lines changed

pandas/util/_decorators.py

-1
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,6 @@ def update(self, *args, **kwargs) -> None:
294294
"""
295295
Update self.params with supplied args.
296296
"""
297-
298297
if isinstance(self.params, dict):
299298
self.params.update(*args, **kwargs)
300299

pandas/util/_depr_module.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44
"""
55

66
import importlib
7+
from typing import Iterable
78
import warnings
89

910

1011
class _DeprecatedModule:
11-
""" Class for mocking deprecated modules.
12+
"""
13+
Class for mocking deprecated modules.
1214
1315
Parameters
1416
----------
@@ -34,7 +36,7 @@ def __init__(self, deprmod, deprmodto=None, removals=None, moved=None):
3436
# For introspection purposes.
3537
self.self_dir = frozenset(dir(type(self)))
3638

37-
def __dir__(self):
39+
def __dir__(self) -> Iterable[str]:
3840
deprmodule = self._import_deprmod()
3941
return dir(deprmodule)
4042

pandas/util/_doctools.py

+16-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional, Tuple
2+
13
import numpy as np
24

35
import pandas as pd
@@ -9,24 +11,27 @@ class TablePlotter:
911
Used in merging.rst
1012
"""
1113

12-
def __init__(self, cell_width=0.37, cell_height=0.25, font_size=7.5):
14+
def __init__(
15+
self,
16+
cell_width: float = 0.37,
17+
cell_height: float = 0.25,
18+
font_size: float = 7.5,
19+
):
1320
self.cell_width = cell_width
1421
self.cell_height = cell_height
1522
self.font_size = font_size
1623

17-
def _shape(self, df):
24+
def _shape(self, df: pd.DataFrame) -> Tuple[int, int]:
1825
"""
1926
Calculate table chape considering index levels.
2027
"""
21-
2228
row, col = df.shape
2329
return row + df.columns.nlevels, col + df.index.nlevels
2430

25-
def _get_cells(self, left, right, vertical):
31+
def _get_cells(self, left, right, vertical) -> Tuple[int, int]:
2632
"""
2733
Calculate appropriate figure size based on left and right data.
2834
"""
29-
3035
if vertical:
3136
# calculate required number of cells
3237
vcells = max(sum(self._shape(l)[0] for l in left), self._shape(right)[0])
@@ -36,7 +41,7 @@ def _get_cells(self, left, right, vertical):
3641
hcells = sum([self._shape(l)[1] for l in left] + [self._shape(right)[1]])
3742
return hcells, vcells
3843

39-
def plot(self, left, right, labels=None, vertical=True):
44+
def plot(self, left, right, labels=None, vertical: bool = True):
4045
"""
4146
Plot left / right DataFrames in specified layout.
4247
@@ -45,7 +50,7 @@ def plot(self, left, right, labels=None, vertical=True):
4550
left : list of DataFrames before operation is applied
4651
right : DataFrame of operation result
4752
labels : list of str to be drawn as titles of left DataFrames
48-
vertical : bool
53+
vertical : bool, default True
4954
If True, use vertical layout. If False, use horizontal layout.
5055
"""
5156
import matplotlib.pyplot as plt
@@ -96,7 +101,9 @@ def plot(self, left, right, labels=None, vertical=True):
96101
return fig
97102

98103
def _conv(self, data):
99-
"""Convert each input to appropriate for table outplot"""
104+
"""
105+
Convert each input to appropriate for table outplot.
106+
"""
100107
if isinstance(data, pd.Series):
101108
if data.name is None:
102109
data = data.to_frame(name="")
@@ -127,7 +134,7 @@ def _insert_index(self, data):
127134
data.columns = col
128135
return data
129136

130-
def _make_table(self, ax, df, title, height=None):
137+
def _make_table(self, ax, df, title: str, height: Optional[float] = None):
131138
if df is None:
132139
ax.set_visible(False)
133140
return

pandas/util/_exceptions.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
@contextlib.contextmanager
66
def rewrite_exception(old_name: str, new_name: str):
7-
"""Rewrite the message of an exception."""
7+
"""
8+
Rewrite the message of an exception.
9+
"""
810
try:
911
yield
1012
except Exception as err:

pandas/util/_print_versions.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212

1313

1414
def get_sys_info() -> List[Tuple[str, Optional[Union[str, int]]]]:
15-
"Returns system information as a list"
16-
15+
"""
16+
Returns system information as a list
17+
"""
1718
blob: List[Tuple[str, Optional[Union[str, int]]]] = []
1819

1920
# get full commit hash
@@ -123,7 +124,7 @@ def show_versions(as_json=False):
123124
print(tpl.format(k=k, stat=stat))
124125

125126

126-
def main():
127+
def main() -> int:
127128
from optparse import OptionParser
128129

129130
parser = OptionParser()

pandas/util/_test_decorators.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def test_foo():
3737
from pandas.core.computation.expressions import _NUMEXPR_INSTALLED, _USE_NUMEXPR
3838

3939

40-
def safe_import(mod_name, min_version=None):
40+
def safe_import(mod_name: str, min_version: Optional[str] = None):
4141
"""
4242
Parameters:
4343
-----------
@@ -110,7 +110,7 @@ def _skip_if_not_us_locale():
110110
return True
111111

112112

113-
def _skip_if_no_scipy():
113+
def _skip_if_no_scipy() -> bool:
114114
return not (
115115
safe_import("scipy.stats")
116116
and safe_import("scipy.sparse")
@@ -195,7 +195,9 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable:
195195
)
196196

197197

198-
def skip_if_np_lt(ver_str, reason=None, *args, **kwds):
198+
def skip_if_np_lt(
199+
ver_str: str, reason: Optional[str] = None, *args, **kwds
200+
) -> Callable:
199201
if reason is None:
200202
reason = f"NumPy {ver_str} or greater required"
201203
return pytest.mark.skipif(
@@ -211,14 +213,14 @@ def parametrize_fixture_doc(*args):
211213
initial fixture docstring by replacing placeholders {0}, {1} etc
212214
with parameters passed as arguments.
213215
214-
Parameters:
216+
Parameters
215217
----------
216-
args: iterable
217-
Positional arguments for docstring.
218+
args: iterable
219+
Positional arguments for docstring.
218220
219-
Returns:
221+
Returns
220222
-------
221-
documented_fixture: function
223+
function
222224
The decorated function wrapped within a pytest
223225
``parametrize_fixture_doc`` mark
224226
"""
@@ -230,7 +232,7 @@ def documented_fixture(fixture):
230232
return documented_fixture
231233

232234

233-
def check_file_leaks(func):
235+
def check_file_leaks(func) -> Callable:
234236
"""
235237
Decorate a test function tot check that we are not leaking file descriptors.
236238
"""

pandas/util/_tester.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
Entrypoint for testing from the top-level namespace
2+
Entrypoint for testing from the top-level namespace.
33
"""
44
import os
55
import sys
@@ -22,7 +22,8 @@ def test(extra_args=None):
2222
extra_args = [extra_args]
2323
cmd = extra_args
2424
cmd += [PKG]
25-
print(f"running: pytest {' '.join(cmd)}")
25+
joined = " ".join(cmd)
26+
print(f"running: pytest {joined}")
2627
sys.exit(pytest.main(cmd))
2728

2829

pandas/util/_validators.py

+16-29
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ def _check_arg_length(fname, args, max_fname_arg_count, compat_args):
1515
Checks whether 'args' has length of at most 'compat_args'. Raises
1616
a TypeError if that is not the case, similar to in Python when a
1717
function is called with too many arguments.
18-
1918
"""
2019
if max_fname_arg_count < 0:
2120
raise ValueError("'max_fname_arg_count' must be non-negative")
@@ -38,7 +37,6 @@ def _check_for_default_values(fname, arg_val_dict, compat_args):
3837
3938
Note that this function is to be called only when it has been
4039
checked that arg_val_dict.keys() is a subset of compat_args
41-
4240
"""
4341
for key in arg_val_dict:
4442
# try checking equality directly with '=' operator,
@@ -65,11 +63,8 @@ def _check_for_default_values(fname, arg_val_dict, compat_args):
6563

6664
if not match:
6765
raise ValueError(
68-
(
69-
f"the '{key}' parameter is not "
70-
"supported in the pandas "
71-
f"implementation of {fname}()"
72-
)
66+
f"the '{key}' parameter is not supported in "
67+
f"the pandas implementation of {fname}()"
7368
)
7469

7570

@@ -79,19 +74,18 @@ def validate_args(fname, args, max_fname_arg_count, compat_args):
7974
has at most `len(compat_args)` arguments and whether or not all of these
8075
elements in `args` are set to their default values.
8176
82-
fname: str
77+
Parameters
78+
----------
79+
fname : str
8380
The name of the function being passed the `*args` parameter
84-
85-
args: tuple
81+
args : tuple
8682
The `*args` parameter passed into a function
87-
88-
max_fname_arg_count: int
83+
max_fname_arg_count : int
8984
The maximum number of arguments that the function `fname`
9085
can accept, excluding those in `args`. Used for displaying
9186
appropriate error messages. Must be non-negative.
92-
93-
compat_args: OrderedDict
94-
A ordered dictionary of keys and their associated default values.
87+
compat_args : Dict
88+
An ordered dictionary of keys and their associated default values.
9589
In order to accommodate buggy behaviour in some versions of `numpy`,
9690
where a signature displayed keyword arguments but then passed those
9791
arguments **positionally** internally when calling downstream
@@ -101,10 +95,11 @@ def validate_args(fname, args, max_fname_arg_count, compat_args):
10195
10296
Raises
10397
------
104-
TypeError if `args` contains more values than there are `compat_args`
105-
ValueError if `args` contains values that do not correspond to those
106-
of the default values specified in `compat_args`
107-
98+
TypeError
99+
If `args` contains more values than there are `compat_args`
100+
ValueError
101+
If `args` contains values that do not correspond to those
102+
of the default values specified in `compat_args`
108103
"""
109104
_check_arg_length(fname, args, max_fname_arg_count, compat_args)
110105

@@ -119,7 +114,6 @@ def _check_for_invalid_keys(fname, kwargs, compat_args):
119114
"""
120115
Checks whether 'kwargs' contains any keys that are not
121116
in 'compat_args' and raises a TypeError if there is one.
122-
123117
"""
124118
# set(dict) --> set of the dictionary's keys
125119
diff = set(kwargs) - set(compat_args)
@@ -139,12 +133,10 @@ def validate_kwargs(fname, kwargs, compat_args):
139133
140134
Parameters
141135
----------
142-
fname: str
136+
fname : str
143137
The name of the function being passed the `**kwargs` parameter
144-
145-
kwargs: dict
138+
kwargs : dict
146139
The `**kwargs` parameter passed into `fname`
147-
148140
compat_args: dict
149141
A dictionary of keys that `kwargs` is allowed to have and their
150142
associated default values
@@ -154,7 +146,6 @@ def validate_kwargs(fname, kwargs, compat_args):
154146
TypeError if `kwargs` contains keys not in `compat_args`
155147
ValueError if `kwargs` contains keys in `compat_args` that do not
156148
map to the default values specified in `compat_args`
157-
158149
"""
159150
kwds = kwargs.copy()
160151
_check_for_invalid_keys(fname, kwargs, compat_args)
@@ -171,18 +162,14 @@ def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_ar
171162
----------
172163
fname: str
173164
The name of the function being passed the `**kwargs` parameter
174-
175165
args: tuple
176166
The `*args` parameter passed into a function
177-
178167
kwargs: dict
179168
The `**kwargs` parameter passed into `fname`
180-
181169
max_fname_arg_count: int
182170
The minimum number of arguments that the function `fname`
183171
requires, excluding those in `args`. Used for displaying
184172
appropriate error messages. Must be non-negative.
185-
186173
compat_args: OrderedDict
187174
A ordered dictionary of keys that `kwargs` is allowed to
188175
have and their associated default values. Note that if there

0 commit comments

Comments
 (0)