Skip to content

Commit 2926047

Browse files
committed
Explain typed etc.
1 parent 0b935ce commit 2926047

File tree

11 files changed

+76
-64
lines changed

11 files changed

+76
-64
lines changed

pandas/_testing.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
)
2323

2424
import pandas._libs.testing as _testing
25-
from pandas._typing import FrameOrSeriesT
25+
from pandas._typing import SameFrameOrSeries
2626
from pandas.compat import _get_lzma_file, _import_lzma
2727

2828
from pandas.core.dtypes.common import (
@@ -102,8 +102,8 @@ def reset_display_options():
102102

103103

104104
def round_trip_pickle(
105-
obj: FrameOrSeriesT, path: Optional[str] = None
106-
) -> FrameOrSeriesT:
105+
obj: SameFrameOrSeries, path: Optional[str] = None
106+
) -> SameFrameOrSeries:
107107
"""
108108
Pickle an object and then read it again.
109109

pandas/_typing.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,16 @@
4242

4343
Dtype = Union[str, np.dtype, "ExtensionDtype"]
4444
FilePathOrBuffer = Union[str, Path, IO[AnyStr]]
45+
# FrameOrSeries means either a DataFrame or a Series. E.g.
46+
# `def func(a: FrameOrSeries) -> FrameOrSeries: ...` means that if a Series is passed
47+
# in, either a Series or DataFrame is returned, and if a DataFrame is passed in, either
48+
# a DataFrame or a Series is returned.
4549
FrameOrSeries = Union["DataFrame", "Series"]
46-
FrameOrSeriesT = TypeVar("FrameOrSeriesT", bound="NDFrame")
50+
# SameFrameOrSeries is stricter and ensures that the same subclass of NDFrame always is
51+
# used. E.g. `def func(a: SameFrameOrSeries) -> SameFrameOrSeries: ...` means that if a
52+
# Series is passed into a function, a Series is always returned and if a DataFrame is
53+
# passed in, a DataFrame is always returned.
54+
SameFrameOrSeries = TypeVar("SameFrameOrSeries", bound="NDFrame")
4755
Axis = Union[str, int]
4856
Ordered = Optional[bool]
4957
JSONSerializable = Union[PythonScalar, List, Dict]

pandas/core/generic.py

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from pandas._config import config
3131

3232
from pandas._libs import Timestamp, iNaT, lib, properties
33-
from pandas._typing import Dtype, FilePathOrBuffer, FrameOrSeriesT, JSONSerializable
33+
from pandas._typing import Dtype, FilePathOrBuffer, JSONSerializable, SameFrameOrSeries
3434
from pandas.compat import set_function_name
3535
from pandas.compat._optional import import_optional_dependency
3636
from pandas.compat.numpy import function as nv
@@ -552,12 +552,12 @@ def size(self):
552552
return np.prod(self.shape)
553553

554554
@property
555-
def _selected_obj(self: FrameOrSeriesT) -> FrameOrSeriesT:
555+
def _selected_obj(self: SameFrameOrSeries) -> SameFrameOrSeries:
556556
""" internal compat with SelectionMixin """
557557
return self
558558

559559
@property
560-
def _obj_with_exclusions(self: FrameOrSeriesT) -> FrameOrSeriesT:
560+
def _obj_with_exclusions(self: SameFrameOrSeries) -> SameFrameOrSeries:
561561
""" internal compat with SelectionMixin """
562562
return self
563563

@@ -4670,7 +4670,7 @@ def f(x):
46704670
else:
46714671
raise TypeError("Must pass either `items`, `like`, or `regex`")
46724672

4673-
def head(self: FrameOrSeriesT, n: int = 5) -> FrameOrSeriesT:
4673+
def head(self: SameFrameOrSeries, n: int = 5) -> SameFrameOrSeries:
46744674
"""
46754675
Return the first `n` rows.
46764676
@@ -4743,7 +4743,7 @@ def head(self: FrameOrSeriesT, n: int = 5) -> FrameOrSeriesT:
47434743

47444744
return self.iloc[:n]
47454745

4746-
def tail(self: FrameOrSeriesT, n: int = 5) -> FrameOrSeriesT:
4746+
def tail(self: SameFrameOrSeries, n: int = 5) -> SameFrameOrSeries:
47474747
"""
47484748
Return the last `n` rows.
47494749
@@ -5188,8 +5188,8 @@ def pipe(self, func, *args, **kwargs):
51885188
# Attribute access
51895189

51905190
def __finalize__(
5191-
self: FrameOrSeriesT, other, method=None, **kwargs
5192-
) -> FrameOrSeriesT:
5191+
self: SameFrameOrSeries, other, method=None, **kwargs
5192+
) -> SameFrameOrSeries:
51935193
"""
51945194
Propagate metadata from other to self.
51955195
@@ -5658,7 +5658,7 @@ def astype(
56585658
result.columns = self.columns
56595659
return result
56605660

5661-
def copy(self: FrameOrSeriesT, deep: bool_t = True) -> FrameOrSeriesT:
5661+
def copy(self: SameFrameOrSeries, deep: bool_t = True) -> SameFrameOrSeries:
56625662
"""
56635663
Make a copy of this object's indices and data.
56645664
@@ -5766,10 +5766,10 @@ def copy(self: FrameOrSeriesT, deep: bool_t = True) -> FrameOrSeriesT:
57665766
data = self._data.copy(deep=deep)
57675767
return self._constructor(data).__finalize__(self)
57685768

5769-
def __copy__(self: FrameOrSeriesT, deep: bool_t = True) -> FrameOrSeriesT:
5769+
def __copy__(self: SameFrameOrSeries, deep: bool_t = True) -> SameFrameOrSeries:
57705770
return self.copy(deep=deep)
57715771

5772-
def __deepcopy__(self: FrameOrSeriesT, memo=None) -> FrameOrSeriesT:
5772+
def __deepcopy__(self: SameFrameOrSeries, memo=None) -> SameFrameOrSeries:
57735773
"""
57745774
Parameters
57755775
----------
@@ -5779,13 +5779,13 @@ def __deepcopy__(self: FrameOrSeriesT, memo=None) -> FrameOrSeriesT:
57795779
return self.copy(deep=True)
57805780

57815781
def _convert(
5782-
self: FrameOrSeriesT,
5782+
self: SameFrameOrSeries,
57835783
datetime: bool_t = False,
57845784
numeric: bool_t = False,
57855785
timedelta: bool_t = False,
57865786
coerce: bool_t = False,
57875787
copy: bool_t = True,
5788-
) -> FrameOrSeriesT:
5788+
) -> SameFrameOrSeries:
57895789
"""
57905790
Attempt to infer better dtype for object columns
57915791
@@ -5877,14 +5877,14 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries:
58775877
# Filling NA's
58785878

58795879
def fillna(
5880-
self: FrameOrSeriesT,
5880+
self: SameFrameOrSeries,
58815881
value=None,
58825882
method=None,
58835883
axis=None,
58845884
inplace: bool_t = False,
58855885
limit=None,
58865886
downcast=None,
5887-
) -> Optional[FrameOrSeriesT]:
5887+
) -> Optional[SameFrameOrSeries]:
58885888
"""
58895889
Fill NA/NaN values using the specified method.
58905890
@@ -6066,12 +6066,12 @@ def fillna(
60666066
return self._constructor(new_data).__finalize__(self)
60676067

60686068
def ffill(
6069-
self: FrameOrSeriesT,
6069+
self: SameFrameOrSeries,
60706070
axis=None,
60716071
inplace: bool_t = False,
60726072
limit=None,
60736073
downcast=None,
6074-
) -> Optional[FrameOrSeriesT]:
6074+
) -> Optional[SameFrameOrSeries]:
60756075
"""
60766076
Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.
60776077
@@ -6085,12 +6085,12 @@ def ffill(
60856085
)
60866086

60876087
def bfill(
6088-
self: FrameOrSeriesT,
6088+
self: SameFrameOrSeries,
60896089
axis=None,
60906090
inplace: bool_t = False,
60916091
limit=None,
60926092
downcast=None,
6093-
) -> Optional[FrameOrSeriesT]:
6093+
) -> Optional[SameFrameOrSeries]:
60946094
"""
60956095
Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.
60966096
@@ -8055,14 +8055,14 @@ def last(self: FrameOrSeries, offset) -> FrameOrSeries:
80558055
return self.iloc[start:]
80568056

80578057
def rank(
8058-
self: FrameOrSeriesT,
8058+
self: SameFrameOrSeries,
80598059
axis=0,
80608060
method: str = "average",
80618061
numeric_only: Optional[bool_t] = None,
80628062
na_option: str = "keep",
80638063
ascending: bool_t = True,
80648064
pct: bool_t = False,
8065-
) -> FrameOrSeriesT:
8065+
) -> SameFrameOrSeries:
80668066
"""
80678067
Compute numerical data ranks (1 through n) along axis.
80688068
@@ -8870,7 +8870,9 @@ def shift(
88708870

88718871
return self._constructor(new_data).__finalize__(self)
88728872

8873-
def slice_shift(self: FrameOrSeriesT, periods: int = 1, axis=0) -> FrameOrSeriesT:
8873+
def slice_shift(
8874+
self: SameFrameOrSeries, periods: int = 1, axis=0
8875+
) -> SameFrameOrSeries:
88748876
"""
88758877
Equivalent to `shift` without copying data.
88768878
@@ -8970,8 +8972,8 @@ def tshift(
89708972
return self._constructor(new_data).__finalize__(self)
89718973

89728974
def truncate(
8973-
self: FrameOrSeriesT, before=None, after=None, axis=None, copy: bool_t = True
8974-
) -> FrameOrSeriesT:
8975+
self: SameFrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True
8976+
) -> SameFrameOrSeries:
89758977
"""
89768978
Truncate a Series or DataFrame before and after some index value.
89778979
@@ -9124,8 +9126,8 @@ def truncate(
91249126
return result
91259127

91269128
def tz_convert(
9127-
self: FrameOrSeriesT, tz, axis=0, level=None, copy: bool_t = True
9128-
) -> FrameOrSeriesT:
9129+
self: SameFrameOrSeries, tz, axis=0, level=None, copy: bool_t = True
9130+
) -> SameFrameOrSeries:
91299131
"""
91309132
Convert tz-aware axis to target time zone.
91319133
@@ -9181,14 +9183,14 @@ def _tz_convert(ax, tz):
91819183
return result.__finalize__(self)
91829184

91839185
def tz_localize(
9184-
self: FrameOrSeriesT,
9186+
self: SameFrameOrSeries,
91859187
tz,
91869188
axis=0,
91879189
level=None,
91889190
copy: bool_t = True,
91899191
ambiguous="raise",
91909192
nonexistent: str = "raise",
9191-
) -> FrameOrSeriesT:
9193+
) -> SameFrameOrSeries:
91929194
"""
91939195
Localize tz-naive index of a Series or DataFrame to target time zone.
91949196

pandas/core/groupby/generic.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import numpy as np
3131

3232
from pandas._libs import Timestamp, lib
33-
from pandas._typing import FrameOrSeriesT
33+
from pandas._typing import SameFrameOrSeries
3434
from pandas.util._decorators import Appender, Substitution
3535

3636
from pandas.core.dtypes.cast import (
@@ -86,7 +86,7 @@
8686
ScalarResult = typing.TypeVar("ScalarResult")
8787

8888

89-
def generate_property(name: str, klass: Type[FrameOrSeriesT]):
89+
def generate_property(name: str, klass: Type[SameFrameOrSeries]):
9090
"""
9191
Create a property for a GroupBy subclass to dispatch to DataFrame/Series.
9292
@@ -109,7 +109,9 @@ def prop(self):
109109
return property(prop)
110110

111111

112-
def pin_whitelisted_properties(klass: Type[FrameOrSeriesT], whitelist: FrozenSet[str]):
112+
def pin_whitelisted_properties(
113+
klass: Type[SameFrameOrSeries], whitelist: FrozenSet[str]
114+
):
113115
"""
114116
Create GroupBy member defs for DataFrame/Series names in a whitelist.
115117

pandas/core/groupby/groupby.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class providing the base-class of operations.
3333

3434
from pandas._libs import Timestamp
3535
import pandas._libs.groupby as libgroupby
36-
from pandas._typing import FrameOrSeriesT, Scalar
36+
from pandas._typing import SameFrameOrSeries, Scalar
3737
from pandas.compat import set_function_name
3838
from pandas.compat.numpy import function as nv
3939
from pandas.errors import AbstractMethodError
@@ -2439,8 +2439,8 @@ def tail(self, n=5):
24392439
return self._selected_obj[mask]
24402440

24412441
def _reindex_output(
2442-
self, output: FrameOrSeriesT, fill_value: Scalar = np.NaN
2443-
) -> FrameOrSeriesT:
2442+
self, output: SameFrameOrSeries, fill_value: Scalar = np.NaN
2443+
) -> SameFrameOrSeries:
24442444
"""
24452445
If we have categorical groupers, then we might want to make sure that
24462446
we have a fully re-indexed output to the levels. This means expanding

pandas/core/groupby/grouper.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import numpy as np
99

10-
from pandas._typing import FrameOrSeriesT
10+
from pandas._typing import SameFrameOrSeries
1111
from pandas.util._decorators import cache_readonly
1212

1313
from pandas.core.dtypes.common import (
@@ -141,7 +141,7 @@ def _get_grouper(self, obj, validate: bool = True):
141141
)
142142
return self.binner, self.grouper, self.obj
143143

144-
def _set_grouper(self, obj: FrameOrSeriesT, sort: bool = False):
144+
def _set_grouper(self, obj: SameFrameOrSeries, sort: bool = False):
145145
"""
146146
given an object and the specifications, setup the internal grouper
147147
for this particular specification
@@ -244,7 +244,7 @@ def __init__(
244244
self,
245245
index: Index,
246246
grouper=None,
247-
obj: Optional[FrameOrSeriesT] = None,
247+
obj: Optional[SameFrameOrSeries] = None,
248248
name=None,
249249
level=None,
250250
sort: bool = True,
@@ -424,15 +424,15 @@ def groups(self) -> Dict[Hashable, np.ndarray]:
424424

425425

426426
def get_grouper(
427-
obj: FrameOrSeriesT,
427+
obj: SameFrameOrSeries,
428428
key=None,
429429
axis: int = 0,
430430
level=None,
431431
sort: bool = True,
432432
observed: bool = False,
433433
mutated: bool = False,
434434
validate: bool = True,
435-
) -> "Tuple[ops.BaseGrouper, List[Hashable], FrameOrSeriesT]":
435+
) -> "Tuple[ops.BaseGrouper, List[Hashable], SameFrameOrSeries]":
436436
"""
437437
Create and return a BaseGrouper, which is an internal
438438
mapping of how to create the grouper indexers.

0 commit comments

Comments
 (0)