Skip to content

DOC/TYP: index.take return val #40521

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 15 commits into from
May 23, 2021
Merged
Changes from 2 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
24 changes: 17 additions & 7 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,7 @@ def astype(self, dtype, copy=True):

Parameters
----------
indices : list
indices : array_like
Indices to be taken.
axis : int, optional
The axis over which to select values, always 0.
Expand All @@ -897,8 +897,8 @@ def astype(self, dtype, copy=True):

Returns
-------
numpy.ndarray
Elements of given indices.
Index
An index formed of elements at the given indices.

See Also
--------
Expand All @@ -907,16 +907,26 @@ def astype(self, dtype, copy=True):
"""

@Appender(_index_shared_docs["take"] % _index_doc_kwargs)
def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
def take(
self,
indices: Union[ArrayLike, Sequence[int]],
Copy link
Member

Choose a reason for hiding this comment

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

is ArrayLike really needed here? it should also be a Sequence[int]

Copy link
Member

Choose a reason for hiding this comment

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

see #28770 for issue about EA, but applicable to Series, Index and np.ndarray also

from typing import Sequence, cast
import numpy as np
import pandas as pd
from pandas.core.arrays import ExtensionArray

df = pd.DataFrame({"a": [1, 2, 3]})
idx = df.index
arr: np.ndarray = cast(np.ndarray, idx._values)
ea: ExtensionArray = pd.array(arr, dtype="Int64")
ser = pd.Series(arr)
reveal_type(idx)
reveal_type(arr)
reveal_type(ea)
reveal_type(ser)


def func(arr: Sequence):
    pass


func(idx)
func(arr)
func(ea)
func(ser)
/home/simon/t.py:11: note: Revealed type is 'pandas.core.indexes.base.Index'
/home/simon/t.py:12: note: Revealed type is 'numpy.ndarray'
/home/simon/t.py:13: note: Revealed type is 'pandas.core.arrays.base.ExtensionArray'
/home/simon/t.py:14: note: Revealed type is 'pandas.core.series.Series'
/home/simon/t.py:21: error: Argument 1 to "func" has incompatible type "Index"; expected "Sequence[Any]"  [arg-type]
/home/simon/t.py:22: error: Argument 1 to "func" has incompatible type "ndarray"; expected "Sequence[Any]"  [arg-type]
/home/simon/t.py:23: error: Argument 1 to "func" has incompatible type "ExtensionArray"; expected "Sequence[Any]"  [arg-type]
/home/simon/t.py:24: error: Argument 1 to "func" has incompatible type "Series"; expected "Sequence[Any]"  [arg-type]

axis: int = 0,
allow_fill: bool = True,
fill_value=None,
**kwargs,
):
Copy link
Member Author

Choose a reason for hiding this comment

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

Any advice on typing this return value? Can almost use the TypeVar _IndexT, but the problem is that RangeIndex.take returns a superclass (Int64Index).

Copy link
Member

Choose a reason for hiding this comment

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

I think in the base class use Index, and can then use a typevar in the subclasses that do return the same type.

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried something along those lines originally - the problem I was running into is how to handle subclasses which rely on parent implementations. For example, for ExtensionIndex would like to be able to write a stub like

def take(
        self: _ExtensionIndexT,
        indices,
        axis: int = 0,
        allow_fill: bool = True,
        fill_value=None,
        **kwargs,
    ) -> _ExtensionIndexT: ...

to essentially type the child while still relying on the inherited implementation. But couldn't figure out a way to achieve this.

if kwargs:
nv.validate_take((), kwargs)
indices = ensure_platform_int(indices)
allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices)
indices_as_array = ensure_platform_int(indices)
allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices_as_array)

# Note: we discard fill_value and use self._na_value, only relevant
# in the case where allow_fill is True and fill_value is not None
taken = algos.take(
self._values, indices, allow_fill=allow_fill, fill_value=self._na_value
self._values,
indices_as_array,
allow_fill=allow_fill,
fill_value=self._na_value,
)
return type(self)._simple_new(taken, name=self.name)

Expand Down