Skip to content

TYP: Remove _ensure_type #32633

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
Mar 11, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Fixed regressions
- Fixed regression in the repr of an object-dtype :class:`Index` with bools and missing values (:issue:`32146`)
- Fixed regression in :meth:`read_csv` in which the ``encoding`` option was not recognized with certain file-like objects (:issue:`31819`)
- Fixed regression in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with (tz-aware) index and ``method=nearest`` (:issue:`26683`)
- Fixed regression in :meth:`DataFrame.reindex_like` on a :class:`DataFrame` subclass raised an ``AssertionError`` (:issue:`31925`)


.. ---------------------------------------------------------------------------
Expand Down
10 changes: 0 additions & 10 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import numpy as np

import pandas._libs.lib as lib
from pandas._typing import T
from pandas.compat import PYPY
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
Expand Down Expand Up @@ -87,15 +86,6 @@ def __sizeof__(self):
# no memory_usage attribute, so fall back to object's 'sizeof'
return super().__sizeof__()

def _ensure_type(self: T, obj) -> T:
"""
Ensure that an object has same type as self.

Used by type checkers.
"""
assert isinstance(obj, type(self)), type(obj)
return obj


class NoNewAttributesMixin:
"""
Expand Down
20 changes: 9 additions & 11 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3637,7 +3637,7 @@ def reindex(self, *args, **kwargs) -> "DataFrame":
# Pop these, since the values are in `kwargs` under different names
kwargs.pop("axis", None)
kwargs.pop("labels", None)
return self._ensure_type(super().reindex(**kwargs))
return super().reindex(**kwargs)

def drop(
self,
Expand Down Expand Up @@ -3955,8 +3955,8 @@ def replace(

@Appender(_shared_docs["shift"] % _shared_doc_kwargs)
def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "DataFrame":
return self._ensure_type(
super().shift(periods=periods, freq=freq, axis=axis, fill_value=fill_value)
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)

def set_index(
Expand Down Expand Up @@ -8409,14 +8409,12 @@ def isin(self, values) -> "DataFrame":
from pandas.core.reshape.concat import concat

values = collections.defaultdict(list, values)
return self._ensure_type(
concat(
(
self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)
),
axis=1,
)
return concat(
(
self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)
),
axis=1,
)
elif isinstance(values, Series):
if not values.index.is_unique:
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8442,9 +8442,9 @@ def _align_frame(
)

if method is not None:
left = self._ensure_type(
left.fillna(method=method, axis=fill_axis, limit=limit)
)
_left = left.fillna(method=method, axis=fill_axis, limit=limit)
assert _left is not None # needed for mypy
left = _left
right = right.fillna(method=method, axis=fill_axis, limit=limit)

# if DatetimeIndex have different tz, convert to UTC
Expand Down Expand Up @@ -9977,9 +9977,9 @@ def pct_change(
if fill_method is None:
data = self
else:
data = self._ensure_type(
self.fillna(method=fill_method, axis=axis, limit=limit)
)
_data = self.fillna(method=fill_method, axis=axis, limit=limit)
assert _data is not None # needed for mypy
data = _data

rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
if freq is not None:
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ def pivot_table(
table = table.sort_index(axis=1)

if fill_value is not None:
table = table._ensure_type(table.fillna(fill_value, downcast="infer"))
_table = table.fillna(fill_value, downcast="infer")
assert _table is not None # needed for mypy
table = _table

if margins:
if dropna:
Expand Down
4 changes: 1 addition & 3 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,7 @@ def _chk_truncate(self) -> None:
series = series.iloc[:max_rows]
else:
row_num = max_rows // 2
series = series._ensure_type(
concat((series.iloc[:row_num], series.iloc[-row_num:]))
)
series = concat((series.iloc[:row_num], series.iloc[-row_num:]))
self.tr_row_num = row_num
else:
self.tr_row_num = None
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1605,6 +1605,17 @@ def test_reindex_methods(self, method, expected_values):
actual = df[::-1].reindex(target, method=switched_method)
tm.assert_frame_equal(expected, actual)

def test_reindex_subclass(self):
# https://github.com/pandas-dev/pandas/issues/31925
class MyDataFrame(DataFrame):
pass

expected = DataFrame()
df = MyDataFrame()
result = df.reindex_like(expected)

tm.assert_frame_equal(result, expected)

def test_reindex_methods_nearest_special(self):
df = pd.DataFrame({"x": list(range(5))})
target = np.array([-0.1, 0.9, 1.1, 1.5])
Expand Down