Skip to content

TYP: Simple type fixes for ExtensionArray #41255

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 12 commits into from
May 6, 2021
1 change: 1 addition & 0 deletions pandas/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame")

Axis = Union[str, int]
NumpyAxis = Union[Tuple[int], List[int], None]
IndexLabel = Union[Hashable, Sequence[Hashable]]
Level = Union[Hashable, int]
Shape = Tuple[int, ...]
Expand Down
20 changes: 14 additions & 6 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
TYPE_CHECKING,
Any,
Callable,
Iterator,
Sequence,
TypeVar,
cast,
Expand All @@ -24,6 +25,7 @@
from pandas._typing import (
ArrayLike,
Dtype,
NumpyAxis,
PositionalIndexer,
Shape,
)
Expand Down Expand Up @@ -69,6 +71,7 @@
)

if TYPE_CHECKING:
from typing import Literal

class ExtensionArraySupportsAnyAll("ExtensionArray"):
def any(self, *, skipna: bool = True) -> bool:
Expand Down Expand Up @@ -375,7 +378,7 @@ def __len__(self) -> int:
"""
raise AbstractMethodError(self)

def __iter__(self):
def __iter__(self) -> Iterator[Any]:
"""
Iterate over elements of the array.
"""
Expand All @@ -385,7 +388,7 @@ def __iter__(self):
for i in range(len(self)):
yield self[i]

def __contains__(self, item) -> bool | np.bool_:
def __contains__(self, item: Any) -> bool | np.bool_:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we type this with Label elsewhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback I did a grep and only saw Any

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Label is for index values, this is an array, so Any is correct I think

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Label was an alias for Union[Hashable, None] to workaround a mypy bug that has since been fixed. Now mypy recognizes None as being Hashable.

wrt Any

from https://github.com/python/typeshed/blob/master/CONTRIBUTING.md#incomplete-stubs

Included functions and methods must list all arguments, but the arguments can be left unannotated. Do not use Any to mark unannotated arguments or return values.

from https://github.com/python/typeshed/blob/master/CONTRIBUTING.md#conventions

When adding type hints, avoid using the Any type when possible. Reserve the use of Any for when:

the correct type cannot be expressed in the current type system; and
to avoid Union returns (see above).

Note that Any is not the correct type to use if you want to indicate that some function can accept literally anything: in those cases use object instead.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on that explanation, it should be object here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've used object, but had to do a type ignore when any() was called on a comparison. I couldn't figure out how to work around that. See latest commit.

"""
Return for `item in self`.
"""
Expand Down Expand Up @@ -680,7 +683,12 @@ def argmax(self, skipna: bool = True) -> int:
raise NotImplementedError
return nargminmax(self, "argmax")

def fillna(self, value=None, method=None, limit=None):
def fillna(
self,
value: Any | ArrayLike | None = None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = None,
limit: int | None = None,
):
"""
Fill NA/NaN values using the specified method.

Expand Down Expand Up @@ -1207,7 +1215,7 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], str | None]:
# Reshaping
# ------------------------------------------------------------------------

def transpose(self, *axes) -> ExtensionArray:
def transpose(self, axes: NumpyAxis = None) -> ExtensionArray:
"""
Return a transposed view on this array.

Expand All @@ -1220,7 +1228,7 @@ def transpose(self, *axes) -> ExtensionArray:
def T(self) -> ExtensionArray:
return self.transpose()

def ravel(self, order="C") -> ExtensionArray:
def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> ExtensionArray:
"""
Return a flattened view on this array.

Expand Down Expand Up @@ -1294,7 +1302,7 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
"""
raise TypeError(f"cannot perform {name} with type {self.dtype}")

def __hash__(self):
def __hash__(self) -> int:
raise TypeError(f"unhashable type: {repr(type(self).__name__)}")

# ------------------------------------------------------------------------
Expand Down
9 changes: 7 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
Dtype,
DtypeObj,
IndexLabel,
NumpyAxis,
Shape,
final,
)
Expand Down Expand Up @@ -298,15 +299,19 @@ def _values(self) -> ExtensionArray | np.ndarray:
# must be defined here as a property for mypy
raise AbstractMethodError(self)

def transpose(self: _T, *args, **kwargs) -> _T:
def transpose(self: _T, axes: NumpyAxis = None) -> _T:
"""
Return the transpose, which is by definition self.

Returns
-------
%(klass)s
"""
nv.validate_transpose(args, kwargs)
if not (isinstance(axes, list) and isinstance(axes, tuple)):
args = (axes,)
else:
args = axes
nv.validate_transpose(args, {})
return self

T = property(
Expand Down
23 changes: 12 additions & 11 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
IndexLabel,
Level,
NpDtype,
NumpyAxis,
PythonFuncType,
Renamer,
Scalar,
Expand Down Expand Up @@ -3189,7 +3190,7 @@ def memory_usage(self, index: bool = True, deep: bool = False) -> Series:
).append(result)
return result

def transpose(self, *args, copy: bool = False) -> DataFrame:
def transpose(self, axes: NumpyAxis = None, copy: bool = False) -> DataFrame:
"""
Transpose index and columns.

Expand All @@ -3199,7 +3200,7 @@ def transpose(self, *args, copy: bool = False) -> DataFrame:

Parameters
----------
*args : tuple, optional
axes : tuple or list, optional
Accepted for compatibility with NumPy.
copy : bool, default False
Whether to copy the data after transposing, even for DataFrames
Expand Down Expand Up @@ -3286,7 +3287,7 @@ def transpose(self, *args, copy: bool = False) -> DataFrame:
1 object
dtype: object
"""
nv.validate_transpose(args, {})
nv.validate_transpose(axes, {})
# construct the args

dtypes = list(self.dtypes)
Expand Down Expand Up @@ -5015,7 +5016,7 @@ def rename(
def fillna(
self,
value=...,
method: str | None = ...,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
limit=...,
Expand All @@ -5027,7 +5028,7 @@ def fillna(
def fillna(
self,
value,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
Expand Down Expand Up @@ -5060,7 +5061,7 @@ def fillna(
def fillna(
self,
*,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
inplace: Literal[True],
limit=...,
downcast=...,
Expand All @@ -5082,7 +5083,7 @@ def fillna(
def fillna(
self,
*,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
Expand All @@ -5106,7 +5107,7 @@ def fillna(
def fillna(
self,
value,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
*,
inplace: Literal[True],
limit=...,
Expand All @@ -5118,7 +5119,7 @@ def fillna(
def fillna(
self,
value=...,
method: str | None = ...,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = ...,
axis: Axis | None = ...,
inplace: bool = ...,
limit=...,
Expand All @@ -5129,8 +5130,8 @@ def fillna(
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
value=None,
method: str | None = None,
value: Any | ArrayLike | None = None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = None,
axis: Axis | None = None,
inplace: bool = False,
limit=None,
Expand Down
16 changes: 8 additions & 8 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4594,7 +4594,7 @@ def drop(
def fillna(
self,
value=...,
method: str | None = ...,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
limit=...,
Expand All @@ -4606,7 +4606,7 @@ def fillna(
def fillna(
self,
value,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
Expand Down Expand Up @@ -4639,7 +4639,7 @@ def fillna(
def fillna(
self,
*,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
inplace: Literal[True],
limit=...,
downcast=...,
Expand All @@ -4661,7 +4661,7 @@ def fillna(
def fillna(
self,
*,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
Expand All @@ -4685,7 +4685,7 @@ def fillna(
def fillna(
self,
value,
method: str | None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None,
*,
inplace: Literal[True],
limit=...,
Expand All @@ -4697,7 +4697,7 @@ def fillna(
def fillna(
self,
value=...,
method: str | None = ...,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = ...,
axis: Axis | None = ...,
inplace: bool = ...,
limit=...,
Expand All @@ -4709,8 +4709,8 @@ def fillna(
@doc(NDFrame.fillna, **_shared_doc_kwargs) # type: ignore[has-type]
def fillna(
self,
value=None,
method=None,
value: Any | ArrayLike | None = None,
method: Literal["backfill", "bfill", "ffill", "pad"] | None = None,
axis=None,
inplace=False,
limit=None,
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/generic/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ def test_numpy_transpose(self, frame_or_series):
# round-trip preserved
tm.assert_equal(np.transpose(np.transpose(obj)), obj)

msg = "the 'axes' parameter is not supported"
msg = r"(the 'axes' parameter is not supported|axes don't match array)"
with pytest.raises(ValueError, match=msg):
np.transpose(obj, axes=1)

Expand Down