Skip to content

TYP: type some un-typed decorators #43400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from pandas._typing import (
AnyArrayLike,
DtypeObj,
F,
Scalar,
Shape,
npt,
Expand Down Expand Up @@ -185,7 +186,7 @@ def _codes_to_ints(self, codes):
return np.bitwise_or.reduce(codes, axis=1)


def names_compat(meth):
def names_compat(meth: F) -> F:
"""
A decorator to allow either `name` or `names` keyword but not both.

Expand All @@ -201,7 +202,7 @@ def new_meth(self_or_cls, *args, **kwargs):

return meth(self_or_cls, *args, **kwargs)

return new_meth
return cast(F, new_meth)


class MultiIndex(Index):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def set_use_bottleneck(v: bool = True) -> None:


class disallow:
def __init__(self, *dtypes):
def __init__(self, *dtypes: Dtype):
super().__init__()
self.dtypes = tuple(pandas_dtype(dtype).type for dtype in dtypes)

Expand Down Expand Up @@ -449,7 +449,7 @@ def _na_for_min_count(values: np.ndarray, axis: int | None) -> Scalar | np.ndarr
return np.full(result_shape, fill_value, dtype=values.dtype)


def maybe_operate_rowwise(func):
def maybe_operate_rowwise(func: F) -> F:
"""
NumPy operations on C-contiguous ndarrays with axis=1 can be
very slow. Operate row-by-row and concatenate the results.
Expand All @@ -475,7 +475,7 @@ def newfunc(values: np.ndarray, *, axis: int | None = None, **kwargs):

return func(values, axis=axis, **kwargs)

return newfunc
return cast(F, newfunc)


def nanany(
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/window/expanding.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class Expanding(RollingAndExpandingMixin):
4 7.0
"""

_attributes = ["min_periods", "center", "axis", "method"]
_attributes: list[str] = ["min_periods", "center", "axis", "method"]

def __init__(
self,
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/window/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ class BaseWindowGroupby(BaseWindow):

_grouper: BaseGrouper
_as_index: bool
_attributes = ["_grouper"]
_attributes: list[str] = ["_grouper"]

def __init__(
self,
Expand Down Expand Up @@ -1500,7 +1500,7 @@ def corr_func(x, y):

class Rolling(RollingAndExpandingMixin):

_attributes = [
_attributes: list[str] = [
"window",
"min_periods",
"center",
Expand Down
6 changes: 3 additions & 3 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -4549,10 +4549,10 @@ def read(

# we could have a multi-index constructor here
# ensure_index doesn't recognized our list-of-tuples here
if info.get("type") == "MultiIndex":
cols = MultiIndex.from_tuples(index_vals)
else:
if info.get("type") != "MultiIndex":
cols = Index(index_vals)
else:
cols = MultiIndex.from_tuples(index_vals)

names = info.get("names")
if names is not None:
Expand Down
10 changes: 7 additions & 3 deletions pandas/plotting/_matplotlib/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
tzinfo,
)
import functools
from typing import Any
from typing import (
Any,
cast,
)

from dateutil.relativedelta import relativedelta
import matplotlib.dates as dates
Expand All @@ -28,6 +31,7 @@
)
from pandas._libs.tslibs.dtypes import FreqGroup
from pandas._libs.tslibs.offsets import BaseOffset
from pandas._typing import F

from pandas.core.dtypes.common import (
is_float,
Expand Down Expand Up @@ -76,7 +80,7 @@ def get_pairs():
return pairs


def register_pandas_matplotlib_converters(func):
def register_pandas_matplotlib_converters(func: F) -> F:
"""
Decorator applying pandas_converters.
"""
Expand All @@ -86,7 +90,7 @@ def wrapper(*args, **kwargs):
with pandas_converters():
return func(*args, **kwargs)

return wrapper
return cast(F, wrapper)


@contextlib.contextmanager
Expand Down
18 changes: 13 additions & 5 deletions pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,8 +1248,9 @@ def _make_plot(self):
left, right = get_xlim(lines)
ax.set_xlim(left, right)

# error: Signature of "_plot" incompatible with supertype "MPLPlot"
@classmethod
def _plot(
def _plot( # type: ignore[override]
cls, ax: Axes, x, y, style=None, column_num=None, stacking_id=None, **kwds
):
# column_num is used to get the target column from plotf in line and
Expand Down Expand Up @@ -1383,16 +1384,17 @@ def __init__(self, data, **kwargs):
if self.logy or self.loglog:
raise ValueError("Log-y scales are not supported in area plot")

# error: Signature of "_plot" incompatible with supertype "MPLPlot"
@classmethod
def _plot(
def _plot( # type: ignore[override]
cls,
ax: Axes,
x,
y,
style=None,
column_num=None,
stacking_id=None,
is_errorbar=False,
is_errorbar: bool = False,
**kwds,
):

Expand Down Expand Up @@ -1483,8 +1485,11 @@ def _args_adjust(self):
if is_list_like(self.left):
self.left = np.array(self.left)

# error: Signature of "_plot" incompatible with supertype "MPLPlot"
@classmethod
def _plot(cls, ax: Axes, x, y, w, start=0, log=False, **kwds):
def _plot( # type: ignore[override]
cls, ax: Axes, x, y, w, start=0, log=False, **kwds
):
return ax.bar(x, y, w, bottom=start, log=log, **kwds)

@property
Expand Down Expand Up @@ -1601,8 +1606,11 @@ class BarhPlot(BarPlot):
def _start_base(self):
return self.left

# error: Signature of "_plot" incompatible with supertype "MPLPlot"
@classmethod
def _plot(cls, ax: Axes, x, y, w, start=0, log=False, **kwds):
def _plot( # type: ignore[override]
cls, ax: Axes, x, y, w, start=0, log=False, **kwds
):
return ax.barh(x, y, w, left=start, log=log, **kwds)

def _decorate_ticks(self, ax: Axes, name, ticklabels, start_edge, end_edge):
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/frame/methods/test_sort_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,22 +441,22 @@ def test_sort_index_ignore_index(
{"M1": [1, 2], "M2": [3, 4]},
True,
False,
MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")),
MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB")),
),
(
{"M1": [1, 2], "M2": [3, 4]},
{"M1": [2, 1], "M2": [4, 3]},
False,
False,
MultiIndex.from_tuples([[3, 4], [2, 1]], names=list("AB")),
MultiIndex.from_tuples([(3, 4), (2, 1)], names=list("AB")),
),
],
)
def test_sort_index_ignore_index_multi_index(
self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index
):
# GH 30114, this is to test ignore_index on MulitIndex of index
mi = MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB"))
mi = MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB"))
df = DataFrame(original_dict, index=mi)
expected_df = DataFrame(sorted_dict, index=output_index)

Expand Down