Skip to content

Commit bd1dfbd

Browse files
GH804 Potential Index.names typehint
1 parent 21a7794 commit bd1dfbd

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

pandas-stubs/core/indexes/base.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,9 +289,9 @@ class Index(IndexOpsMixin[S1]):
289289
@name.setter
290290
def name(self, value) -> None: ...
291291
@property
292-
def names(self) -> SequenceNotStr: ...
292+
def names(self) -> list[_str | None]: ...
293293
@names.setter
294-
def names(self, names: SequenceNotStr): ...
294+
def names(self, names: SequenceNotStr[_str | None]): ...
295295
def set_names(self, names, *, level=..., inplace: bool = ...): ...
296296
@overload
297297
def rename(self, name, inplace: Literal[False] = False) -> Self: ...

tests/test_indexes.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,17 @@ def test_column_contains() -> None:
8181
# https://github.com/microsoft/python-type-stubs/issues/199
8282
df = pd.DataFrame({"A": [1, 2], "B": ["c", "d"], "E": [3, 4]})
8383

84-
collist = [column for column in df.columns]
85-
86-
collist2 = [column for column in df.columns[df.columns.str.contains("A|B")]]
87-
88-
length = len(df.columns[df.columns.str.contains("A|B")])
84+
# check accessing the columns as Scalar
85+
check(assert_type([column for column in df.columns], list[str]), list)
86+
# check slicing the columns with a Series[bool]
87+
check(
88+
assert_type(
89+
[column for column in df.columns[df.columns.str.contains("A|B")]], list[str]
90+
),
91+
list,
92+
)
93+
# check that generic methods are defined on a slice of an index
94+
check(assert_type(len(df.columns[df.columns.str.contains("A|B")]), int), int)
8995

9096

9197
def test_column_sequence() -> None:
@@ -1163,11 +1169,19 @@ def test_value_counts() -> None:
11631169

11641170

11651171
def test_index_naming() -> None:
1166-
"""Test that we can set the names of an index as a hashable."""
1172+
"""
1173+
Test index names type both for the getter and the setter.
1174+
1175+
The names of an index should be settable with a sequence (not str) and names
1176+
property is a list[str | None] (FrozenList).
1177+
"""
11671178
df = pd.DataFrame({"a": ["a", "b", "c"], "i": [10, 11, 12]})
11681179

11691180
df.index.names = ["idx"]
1170-
1181+
check(assert_type(df.index.names, list[str | None]), list)
11711182
df.index.names = ("idx2",)
1183+
check(assert_type(df.index.names, list[str | None]), list)
11721184
df.index.names = [None]
1185+
check(assert_type(df.index.names, list[str | None]), list)
11731186
df.index.names = (None,)
1187+
check(assert_type(df.index.names, list[str | None]), list)

0 commit comments

Comments
 (0)