Skip to content

Commit f67e4fa

Browse files
committed
Add get method to Series
1 parent bd2fa5a commit f67e4fa

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

pandas-stubs/core/series.pyi

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ from typing import (
1818
ClassVar,
1919
Generic,
2020
Literal,
21+
TypeVar,
2122
overload,
2223
)
2324

@@ -160,6 +161,8 @@ from pandas.plotting import PlotAccessor
160161
_bool = bool
161162
_str = str
162163

164+
_T = TypeVar("_T")
165+
163166
class _iLocIndexerSeries(_iLocIndexer, Generic[S1]):
164167
# get item
165168
@overload
@@ -371,6 +374,10 @@ class Series(IndexOpsMixin[S1], NDFrame):
371374
@overload
372375
def __getitem__(self, idx: Scalar) -> S1: ...
373376
def __setitem__(self, key, value) -> None: ...
377+
@overload
378+
def get(self, key: Hashable, default: None = ...) -> S1 | None: ...
379+
@overload
380+
def get(self, key: Hashable, default: S1 | _T = ...) -> S1 | _T: ...
374381
def repeat(
375382
self, repeats: int | list[int], axis: AxisIndex | None = ...
376383
) -> Series[S1]: ...

tests/test_series.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
Any,
1717
Generic,
1818
TypeVar,
19+
Union,
1920
cast,
2021
)
2122

@@ -2880,6 +2881,24 @@ def test_round() -> None:
28802881
check(assert_type(round(pd.Series([1], dtype=int)), "pd.Series[int]"), pd.Series)
28812882

28822883

2884+
def test_get() -> None:
2885+
s_int = pd.Series([1, 2, 3], index=[1, 2, 3])
2886+
2887+
check(assert_type(s_int.get(1), Union[int, None]), np.int64)
2888+
check(assert_type(s_int.get(99), Union[int, None]), type(None))
2889+
check(assert_type(s_int.get(1, default=None), Union[int, None]), np.int64)
2890+
check(assert_type(s_int.get(1, default=2), int), np.int64)
2891+
check(assert_type(s_int.get(99, default="a"), Union[int, str]), str)
2892+
2893+
s_str = pd.Series(list("abc"), index=list("abc"))
2894+
2895+
check(assert_type(s_str.get("a"), Union[str, None]), str)
2896+
check(assert_type(s_str.get("z"), Union[str, None]), type(None))
2897+
check(assert_type(s_str.get("a", default=None), Union[str, None]), str)
2898+
check(assert_type(s_str.get("a", default="b"), str), str)
2899+
check(assert_type(s_str.get("z", default=True), Union[str, bool]), bool)
2900+
2901+
28832902
def test_series_new_empty() -> None:
28842903
# GH 826
28852904
check(assert_type(pd.Series(), "pd.Series[Any]"), pd.Series)

0 commit comments

Comments
 (0)