Skip to content

Commit 973f04e

Browse files
ueshinHyukjinKwon
authored andcommitted
[SPARK-36961][PYTHON] Use PEP526 style variable type hints
### What changes were proposed in this pull request? Uses PEP526 style variable type hints. ### Why are the changes needed? Now that we have started using newer Python syntax in the code base. We should use PEP526 style variable type hints. - https://www.python.org/dev/peps/pep-0526/ ### Does this PR introduce _any_ user-facing change? No. ### How was this patch tested? Existing tests. Closes #34227 from ueshin/issues/SPARK-36961/pep526. Authored-by: Takuya UESHIN <ueshin@databricks.com> Signed-off-by: Hyukjin Kwon <gurwls223@apache.org>
1 parent 3a91b9a commit 973f04e

19 files changed

Lines changed: 186 additions & 157 deletions

python/pyspark/pandas/accessors.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ def apply_batch(
343343
original_func = func
344344
func = lambda o: original_func(o, *args, **kwds)
345345

346-
self_applied = DataFrame(self._psdf._internal.resolved_copy) # type: DataFrame
346+
self_applied: DataFrame = DataFrame(self._psdf._internal.resolved_copy)
347347

348348
if should_infer_schema:
349349
# Here we execute with the first 1000 to get the return type.
@@ -356,7 +356,7 @@ def apply_batch(
356356
"The given function should return a frame; however, "
357357
"the return type was %s." % type(applied)
358358
)
359-
psdf = ps.DataFrame(applied) # type: DataFrame
359+
psdf: DataFrame = DataFrame(applied)
360360
if len(pdf) <= limit:
361361
return psdf
362362

@@ -632,7 +632,7 @@ def udf(pdf: pd.DataFrame) -> pd.Series:
632632
[field.struct_field for field in index_fields + data_fields]
633633
)
634634

635-
self_applied = DataFrame(self._psdf._internal.resolved_copy) # type: DataFrame
635+
self_applied: DataFrame = DataFrame(self._psdf._internal.resolved_copy)
636636

637637
output_func = GroupBy._make_pandas_df_builder_func(
638638
self_applied, func, return_schema, retain_index=True
@@ -893,7 +893,7 @@ def _transform_batch(
893893
limit = ps.get_option("compute.shortcut_limit")
894894
pser = self._psser.head(limit + 1)._to_internal_pandas()
895895
transformed = pser.transform(func)
896-
psser = Series(transformed) # type: Series
896+
psser: Series = Series(transformed)
897897

898898
field = psser._internal.data_fields[0].normalize_spark_type()
899899
else:

python/pyspark/pandas/categorical.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,9 @@ def add_categories(
239239
FutureWarning,
240240
)
241241

242+
categories: List[Any]
242243
if is_list_like(new_categories):
243-
categories = list(new_categories) # type: List
244+
categories = list(new_categories)
244245
else:
245246
categories = [new_categories]
246247

@@ -433,8 +434,9 @@ def remove_categories(
433434
FutureWarning,
434435
)
435436

437+
categories: List[Any]
436438
if is_list_like(removals):
437-
categories = [cat for cat in removals if cat is not None] # type: List
439+
categories = [cat for cat in removals if cat is not None]
438440
elif removals is None:
439441
categories = []
440442
else:

python/pyspark/pandas/config.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def validate(self, v: Any) -> None:
116116
# See the examples below:
117117
# >>> from pyspark.pandas.config import show_options
118118
# >>> show_options()
119-
_options = [
119+
_options: List[Option] = [
120120
Option(
121121
key="display.max_rows",
122122
doc=(
@@ -246,9 +246,9 @@ def validate(self, v: Any) -> None:
246246
default="plotly",
247247
types=str,
248248
),
249-
] # type: List[Option]
249+
]
250250

251-
_options_dict = dict(zip((option.key for option in _options), _options)) # type: Dict[str, Option]
251+
_options_dict: Dict[str, Option] = dict(zip((option.key for option in _options), _options))
252252

253253
_key_format = "pandas_on_Spark.{}".format
254254

python/pyspark/pandas/frame.py

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -437,8 +437,9 @@ class DataFrame(Frame, Generic[T]):
437437
4 2 5 4 3 9
438438
"""
439439

440-
@no_type_check
441-
def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False):
440+
def __init__( # type: ignore[no-untyped-def]
441+
self, data=None, index=None, columns=None, dtype=None, copy=False
442+
):
442443
if isinstance(data, InternalFrame):
443444
assert index is None
444445
assert columns is None
@@ -535,7 +536,7 @@ def _update_internal_frame(
535536
not_same_anchor = requires_same_anchor and not same_anchor(internal, psser)
536537

537538
if renamed or not_same_anchor:
538-
psdf = DataFrame(self._internal.select_column(old_label)) # type: DataFrame
539+
psdf: DataFrame = DataFrame(self._internal.select_column(old_label))
539540
psser._update_anchor(psdf)
540541
psser = None
541542
else:
@@ -1261,7 +1262,7 @@ def aggregate(self, func: Union[List[str], Dict[Name, List[str]]]) -> "DataFrame
12611262
)
12621263

12631264
with option_context("compute.default_index_type", "distributed"):
1264-
psdf = DataFrame(GroupBy._spark_groupby(self, func)) # type: DataFrame
1265+
psdf: DataFrame = DataFrame(GroupBy._spark_groupby(self, func))
12651266

12661267
# The codes below basically converts:
12671268
#
@@ -2474,9 +2475,9 @@ def apply_func(pdf: pd.DataFrame) -> pd.DataFrame:
24742475
else:
24752476
return pdf_or_pser
24762477

2477-
self_applied = DataFrame(self._internal.resolved_copy) # type: "DataFrame"
2478+
self_applied: DataFrame = DataFrame(self._internal.resolved_copy)
24782479

2479-
column_labels = None # type: Optional[List[Label]]
2480+
column_labels: Optional[List[Label]] = None
24802481
if should_infer_schema:
24812482
# Here we execute with the first 1000 to get the return type.
24822483
# If the records were less than 1000, it uses pandas API directly for a shortcut.
@@ -2588,7 +2589,7 @@ def apply_func(pdf: pd.DataFrame) -> pd.DataFrame:
25882589
column_labels=column_labels,
25892590
)
25902591

2591-
result = DataFrame(internal) # type: "DataFrame"
2592+
result: DataFrame = DataFrame(internal)
25922593
if should_return_series:
25932594
return first_series(result)
25942595
else:
@@ -2723,7 +2724,7 @@ def transform(
27232724
limit = get_option("compute.shortcut_limit")
27242725
pdf = self.head(limit + 1)._to_internal_pandas()
27252726
transformed = pdf.transform(func, axis, *args, **kwargs)
2726-
psdf = DataFrame(transformed) # type: "DataFrame"
2727+
psdf: DataFrame = DataFrame(transformed)
27272728
if len(pdf) <= limit:
27282729
return psdf
27292730

@@ -2936,7 +2937,7 @@ class locomotion
29362937
internal = self._internal.with_filter(reduce(lambda x, y: x & y, rows))
29372938

29382939
if len(key) == self._internal.index_level:
2939-
psdf = DataFrame(internal) # type: DataFrame
2940+
psdf: DataFrame = DataFrame(internal)
29402941
pdf = psdf.head(2)._to_internal_pandas()
29412942
if len(pdf) == 0:
29422943
raise KeyError(key)
@@ -3555,8 +3556,9 @@ def set_index(
35553556
2014 10 31
35563557
"""
35573558
inplace = validate_bool_kwarg(inplace, "inplace")
3559+
key_list: List[Label]
35583560
if is_name_like_tuple(keys):
3559-
key_list = [cast(Label, keys)] # type: List[Label]
3561+
key_list = [cast(Label, keys)]
35603562
elif is_name_like_value(keys):
35613563
key_list = [(keys,)]
35623564
else:
@@ -5218,9 +5220,10 @@ def dropna(
52185220
elif how not in ("any", "all"):
52195221
raise ValueError("invalid how option: {h}".format(h=how))
52205222

5223+
labels: Optional[List[Label]]
52215224
if subset is not None:
52225225
if isinstance(subset, str):
5223-
labels = [(subset,)] # type: Optional[List[Label]]
5226+
labels = [(subset,)]
52245227
elif isinstance(subset, tuple):
52255228
labels = [subset]
52265229
else:
@@ -5284,7 +5287,7 @@ def dropna(
52845287

52855288
internal = internal.with_filter(cond)
52865289

5287-
psdf = DataFrame(internal)
5290+
psdf: DataFrame = DataFrame(internal)
52885291

52895292
null_counts = []
52905293
for label in internal.column_labels:
@@ -5996,6 +5999,7 @@ def pivot_table(
59965999
if fill_value is not None and isinstance(fill_value, (int, float)):
59976000
sdf = sdf.fillna(fill_value)
59986001

6002+
psdf: DataFrame
59996003
if index is not None:
60006004
index_columns = [self._internal.spark_column_name_for(label) for label in index]
60016005
index_fields = [self._internal.field_for(label) for label in index]
@@ -6034,7 +6038,7 @@ def pivot_table(
60346038
data_spark_columns=[scol_for(sdf, col) for col in data_columns],
60356039
column_label_names=column_label_names,
60366040
)
6037-
psdf = DataFrame(internal) # type: "DataFrame"
6041+
psdf = DataFrame(internal)
60386042
else:
60396043
column_labels = [tuple(list(values[0]) + [column]) for column in data_columns]
60406044
column_label_names = ([cast(Optional[Name], None)] * len(values[0])) + [columns]
@@ -6062,7 +6066,7 @@ def pivot_table(
60626066
index_values = values[-1]
60636067
else:
60646068
index_values = values
6065-
index_map = OrderedDict() # type: Dict[str, Optional[Label]]
6069+
index_map: Dict[str, Optional[Label]] = OrderedDict()
60666070
for i, index_value in enumerate(index_values):
60676071
colname = SPARK_INDEX_NAME_FORMAT(i)
60686072
sdf = sdf.withColumn(colname, SF.lit(index_value))
@@ -6257,10 +6261,11 @@ def columns(self, columns: Union[pd.Index, List[Name]]) -> None:
62576261
)
62586262
)
62596263

6264+
column_label_names: Optional[List]
62606265
if isinstance(columns, pd.Index):
62616266
column_label_names = [
62626267
name if is_name_like_tuple(name) else (name,) for name in columns.names
6263-
] # type: Optional[List]
6268+
]
62646269
else:
62656270
column_label_names = None
62666271

@@ -9008,7 +9013,7 @@ def _reindex_columns(
90089013
"shape (1,{}) doesn't match the shape (1,{})".format(len(col), level)
90099014
)
90109015
fill_value = np.nan if fill_value is None else fill_value
9011-
scols_or_pssers = [] # type: List[Union[Series, Column]]
9016+
scols_or_pssers: List[Union[Series, Column]] = []
90129017
labels = []
90139018
for label in label_columns:
90149019
if label in self._internal.column_labels:
@@ -9437,7 +9442,7 @@ def stack(self) -> DataFrameOrSeries:
94379442
).with_filter(SF.lit(False))
94389443
)
94399444

9440-
column_labels = defaultdict(dict) # type: Union[defaultdict, OrderedDict]
9445+
column_labels: Union[defaultdict, OrderedDict] = defaultdict(dict)
94419446
index_values = set()
94429447
should_returns_series = False
94439448
for label in self._internal.column_labels:
@@ -9498,7 +9503,7 @@ def stack(self) -> DataFrameOrSeries:
94989503
data_spark_columns=[scol_for(sdf, col) for col in data_columns],
94999504
column_label_names=column_label_names,
95009505
)
9501-
psdf = DataFrame(internal) # type: "DataFrame"
9506+
psdf: DataFrame = DataFrame(internal)
95029507

95039508
if should_returns_series:
95049509
return first_series(psdf)
@@ -10181,11 +10186,6 @@ def gen_mapper_fn(
1018110186
) -> Tuple[Callable[[Any], Any], Dtype, DataType]:
1018210187
if isinstance(mapper, dict):
1018310188
mapper_dict = cast(dict, mapper)
10184-
if len(mapper_dict) == 0:
10185-
if errors == "raise":
10186-
raise KeyError("Index include label which is not in the `mapper`.")
10187-
else:
10188-
return DataFrame(self._internal)
1018910189

1019010190
type_set = set(map(lambda x: type(x), mapper_dict.values()))
1019110191
if len(type_set) > 1:
@@ -10439,15 +10439,16 @@ def gen_names(
1043910439
v: Union[Any, Sequence[Any], Dict[Name, Any], Callable[[Name], Any]],
1044010440
curnames: List[Name],
1044110441
) -> List[Label]:
10442+
newnames: List[Name]
1044210443
if is_scalar(v):
10443-
newnames = [cast(Any, v)] # type: List[Name]
10444+
newnames = [cast(Name, v)]
1044410445
elif is_list_like(v) and not is_dict_like(v):
10445-
newnames = list(cast(Sequence[Any], v))
10446+
newnames = list(cast(Sequence[Name], v))
1044610447
elif is_dict_like(v):
10447-
v_dict = cast(Dict[Name, Any], v)
10448+
v_dict = cast(Dict[Name, Name], v)
1044810449
newnames = [v_dict[name] if name in v_dict else name for name in curnames]
1044910450
elif callable(v):
10450-
v_callable = cast(Callable[[Name], Any], v)
10451+
v_callable = cast(Callable[[Name], Name], v)
1045110452
newnames = [v_callable(name) for name in curnames]
1045210453
else:
1045310454
raise ValueError(
@@ -10647,7 +10648,7 @@ def idxmax(self, axis: Axis = 0) -> "Series":
1064710648
)
1064810649
cond = reduce(lambda x, y: x | y, conds)
1064910650

10650-
psdf = DataFrame(self._internal.with_filter(cond)) # type: "DataFrame"
10651+
psdf: DataFrame = DataFrame(self._internal.with_filter(cond))
1065110652

1065210653
return cast(ps.Series, ps.from_pandas(psdf._to_internal_pandas().idxmax()))
1065310654

@@ -10719,7 +10720,7 @@ def idxmin(self, axis: Axis = 0) -> "Series":
1071910720
)
1072010721
cond = reduce(lambda x, y: x | y, conds)
1072110722

10722-
psdf = DataFrame(self._internal.with_filter(cond)) # type: "DataFrame"
10723+
psdf: DataFrame = DataFrame(self._internal.with_filter(cond))
1072310724

1072410725
return cast(ps.Series, ps.from_pandas(psdf._to_internal_pandas().idxmin()))
1072510726

@@ -10912,7 +10913,7 @@ def quantile(
1091210913
"accuracy must be an integer; however, got [%s]" % type(accuracy).__name__
1091310914
)
1091410915

10915-
qq = list(q) if isinstance(q, Iterable) else q # type: Union[float, List[float]]
10916+
qq: Union[float, List[float]] = list(q) if isinstance(q, Iterable) else q
1091610917

1091710918
for v in qq if isinstance(qq, list) else [qq]:
1091810919
if not isinstance(v, float):
@@ -10944,9 +10945,9 @@ def quantile(psser: "Series") -> Column:
1094410945
# |[[0.25, 2, 6], [0.5, 3, 7], [0.75, 4, 8]]|
1094510946
# +-----------------------------------------+
1094610947

10947-
percentile_cols = []
10948-
percentile_col_names = []
10949-
column_labels = []
10948+
percentile_cols: List[Column] = []
10949+
percentile_col_names: List[str] = []
10950+
column_labels: List[Label] = []
1095010951
for label, column in zip(
1095110952
self._internal.column_labels, self._internal.data_spark_column_names
1095210953
):
@@ -10974,7 +10975,7 @@ def quantile(psser: "Series") -> Column:
1097410975
# |[2, 3, 4]|[6, 7, 8]|
1097510976
# +---------+---------+
1097610977

10977-
cols_dict = OrderedDict() # type: OrderedDict
10978+
cols_dict: Dict[str, List[Column]] = OrderedDict()
1097810979
for column in percentile_col_names:
1097910980
cols_dict[column] = list()
1098010981
for i in range(len(qq)):
@@ -11357,7 +11358,7 @@ def explode(self, column: Name) -> "DataFrame":
1135711358
if not is_name_like_value(column):
1135811359
raise TypeError("column must be a scalar")
1135911360

11360-
psdf = DataFrame(self._internal.resolved_copy) # type: "DataFrame"
11361+
psdf: DataFrame = DataFrame(self._internal.resolved_copy)
1136111362
psser = psdf[column]
1136211363
if not isinstance(psser, Series):
1136311364
raise ValueError(
@@ -11422,7 +11423,7 @@ def get_spark_column(psdf: DataFrame, label: Label) -> Column:
1142211423

1142311424
return scol
1142411425

11425-
new_column_labels = [] # type: List[Label]
11426+
new_column_labels: List[Label] = []
1142611427
for label in self._internal.column_labels:
1142711428
# Filtering out only columns of numeric and boolean type column.
1142811429
dtype = self._psser_for(label).spark.data_type

python/pyspark/pandas/generic.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2254,10 +2254,11 @@ def groupby(
22542254
2.0 2 5
22552255
NaN 1 4
22562256
"""
2257+
new_by: List[Union[Label, ps.Series]]
22572258
if isinstance(by, ps.DataFrame):
22582259
raise ValueError("Grouper for '{}' not 1-dimensional".format(type(by).__name__))
22592260
elif isinstance(by, ps.Series):
2260-
new_by = [by] # type: List[Union[Label, ps.Series]]
2261+
new_by = [by]
22612262
elif is_name_like_tuple(by):
22622263
if isinstance(self, ps.Series):
22632264
raise KeyError(by)

0 commit comments

Comments
 (0)