Skip to content

Commit f54945e

Browse files
gwromejreback
authored andcommitted
#26065 Fix Type Annotations in pandas.core.arrays (#26071)
1 parent 5cb006f commit f54945e

File tree

8 files changed

+41
-44
lines changed

8 files changed

+41
-44
lines changed

mypy.ini

-18
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,6 @@ ignore_errors=True
1111
[mypy-pandas.core.api]
1212
ignore_errors=True
1313

14-
[mypy-pandas.core.arrays.array_]
15-
ignore_errors=True
16-
17-
[mypy-pandas.core.arrays.datetimelike]
18-
ignore_errors=True
19-
20-
[mypy-pandas.core.arrays.integer]
21-
ignore_errors=True
22-
23-
[mypy-pandas.core.arrays.interval]
24-
ignore_errors=True
25-
26-
[mypy-pandas.core.arrays.period]
27-
ignore_errors=True
28-
29-
[mypy-pandas.core.arrays.timedeltas]
30-
ignore_errors=True
31-
3214
[mypy-pandas.core.base]
3315
ignore_errors=True
3416

pandas/_typing.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
from pathlib import Path
2-
from typing import IO, AnyStr, Union
2+
from typing import IO, AnyStr, Type, Union
33

44
import numpy as np
55

6+
from pandas._libs import Timestamp
7+
from pandas._libs.tslibs.period import Period
8+
from pandas._libs.tslibs.timedeltas import Timedelta
9+
610
from pandas.core.dtypes.dtypes import ExtensionDtype
711
from pandas.core.dtypes.generic import ABCExtensionArray
812

913
ArrayLike = Union[ABCExtensionArray, np.ndarray]
14+
DatetimeLikeScalar = Type[Union[Period, Timestamp, Timedelta]]
1015
Dtype = Union[str, np.dtype, ExtensionDtype]
1116
FilePathOrBuffer = Union[str, Path, IO[AnyStr]]

pandas/core/arrays/array_.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Optional, Sequence, Union
1+
from typing import Optional, Sequence, Union, cast
22

33
import numpy as np
44

@@ -229,7 +229,7 @@ def array(data: Sequence[object],
229229
dtype = registry.find(dtype) or dtype
230230

231231
if is_extension_array_dtype(dtype):
232-
cls = dtype.construct_array_type()
232+
cls = cast(ExtensionDtype, dtype).construct_array_type()
233233
return cls._from_sequence(data, dtype=dtype, copy=copy)
234234

235235
if dtype is None:

pandas/core/arrays/datetimelike.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from datetime import datetime, timedelta
22
import operator
3-
from typing import Any, Sequence, Tuple, Type, Union
3+
from typing import Any, Sequence, Union, cast
44
import warnings
55

66
import numpy as np
@@ -27,6 +27,7 @@
2727
from pandas.core.dtypes.inference import is_array_like
2828
from pandas.core.dtypes.missing import isna
2929

30+
from pandas._typing import DatetimeLikeScalar
3031
from pandas.core import missing, nanops
3132
from pandas.core.algorithms import (
3233
checked_add_with_arr, take, unique1d, value_counts)
@@ -39,6 +40,7 @@
3940

4041

4142
class AttributesMixin:
43+
_data = None # type: np.ndarray
4244

4345
@property
4446
def _attributes(self):
@@ -56,7 +58,7 @@ def _get_attributes_dict(self):
5658
return {k: getattr(self, k, None) for k in self._attributes}
5759

5860
@property
59-
def _scalar_type(self) -> Union[Type, Tuple[Type]]:
61+
def _scalar_type(self) -> DatetimeLikeScalar:
6062
"""The scalar associated with this datelike
6163
6264
* PeriodArray : Period
@@ -477,14 +479,16 @@ def __setitem__(
477479
if lib.is_scalar(key):
478480
raise ValueError("setting an array element with a sequence.")
479481

480-
if (not is_slice
481-
and len(key) != len(value)
482-
and not com.is_bool_indexer(key)):
483-
msg = ("shape mismatch: value array of length '{}' does not "
484-
"match indexing result of length '{}'.")
485-
raise ValueError(msg.format(len(key), len(value)))
486-
if not is_slice and len(key) == 0:
487-
return
482+
if not is_slice:
483+
key = cast(Sequence, key)
484+
if (len(key) != len(value)
485+
and not com.is_bool_indexer(key)):
486+
msg = ("shape mismatch: value array of length '{}' does "
487+
"not match indexing result of length '{}'.")
488+
raise ValueError(msg.format(
489+
len(key), len(value)))
490+
elif not len(key):
491+
return
488492

489493
value = type(self)._from_sequence(value, dtype=self.dtype)
490494
self._check_compatible_with(value)

pandas/core/arrays/integer.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import copy
22
import sys
3+
from typing import Type
34
import warnings
45

56
import numpy as np
@@ -31,9 +32,9 @@ class _IntegerDtype(ExtensionDtype):
3132
3233
The attributes name & type are set when these subclasses are created.
3334
"""
34-
name = None
35+
name = None # type: str
3536
base = None
36-
type = None
37+
type = None # type: Type
3738
na_value = np.nan
3839

3940
def __repr__(self):

pandas/core/arrays/interval.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -939,8 +939,9 @@ def mid(self):
939939
points) and is either monotonic increasing or monotonic decreasing,
940940
else False
941941
"""
942-
943-
@property
942+
# https://github.com/python/mypy/issues/1362
943+
# Mypy does not support decorated properties
944+
@property # type: ignore
944945
@Appender(_interval_shared_docs['is_non_overlapping_monotonic']
945946
% _shared_docs_kwargs)
946947
def is_non_overlapping_monotonic(self):

pandas/core/arrays/period.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from datetime import timedelta
22
import operator
3-
from typing import Any, Callable, Optional, Sequence, Union
3+
from typing import Any, Callable, List, Optional, Sequence, Union
44

55
import numpy as np
66

@@ -23,7 +23,7 @@
2323
from pandas.core.dtypes.missing import isna, notna
2424

2525
import pandas.core.algorithms as algos
26-
from pandas.core.arrays import ExtensionArray, datetimelike as dtl
26+
from pandas.core.arrays import datetimelike as dtl
2727
import pandas.core.common as com
2828

2929
from pandas.tseries import frequencies
@@ -94,7 +94,7 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps):
9494
9595
Parameters
9696
----------
97-
values : Union[PeriodArray, Series[period], ndarary[int], PeriodIndex]
97+
values : Union[PeriodArray, Series[period], ndarray[int], PeriodIndex]
9898
The data to store. These should be arrays that can be directly
9999
converted to ordinals without inference or copy (PeriodArray,
100100
ndarray[int64]), or a box around such an array (Series[period],
@@ -135,7 +135,7 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps):
135135
_scalar_type = Period
136136

137137
# Names others delegate to us
138-
_other_ops = []
138+
_other_ops = [] # type: List[str]
139139
_bool_ops = ['is_leap_year']
140140
_object_ops = ['start_time', 'end_time', 'freq']
141141
_field_ops = ['year', 'month', 'day', 'hour', 'minute', 'second',
@@ -276,7 +276,8 @@ def _check_compatible_with(self, other):
276276
def dtype(self):
277277
return self._dtype
278278

279-
@property
279+
# read-only property overwriting read/write
280+
@property # type: ignore
280281
def freq(self):
281282
"""
282283
Return the frequency object for this PeriodArray.
@@ -538,7 +539,8 @@ def _sub_period(self, other):
538539
@Appender(dtl.DatetimeLikeArrayMixin._addsub_int_array.__doc__)
539540
def _addsub_int_array(
540541
self,
541-
other: Union[ExtensionArray, np.ndarray, ABCIndexClass],
542+
other: Union[ABCPeriodArray, ABCSeries,
543+
ABCPeriodIndex, np.ndarray],
542544
op: Callable[[Any], Any]
543545
) -> ABCPeriodArray:
544546
assert op in [operator.add, operator.sub]
@@ -778,7 +780,8 @@ def period_array(
778780
data = np.asarray(data)
779781

780782
if freq:
781-
dtype = PeriodDtype(freq)
783+
# typed Optional here because the else block below assigns None
784+
dtype = PeriodDtype(freq) # type: Optional[PeriodDtype]
782785
else:
783786
dtype = None
784787

pandas/core/arrays/timedeltas.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from datetime import timedelta
22
import textwrap
3+
from typing import List
34
import warnings
45

56
import numpy as np
@@ -130,8 +131,8 @@ class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps):
130131
_scalar_type = Timedelta
131132
__array_priority__ = 1000
132133
# define my properties & methods for delegation
133-
_other_ops = []
134-
_bool_ops = []
134+
_other_ops = [] # type: List[str]
135+
_bool_ops = [] # type: List[str]
135136
_object_ops = ['freq']
136137
_field_ops = ['days', 'seconds', 'microseconds', 'nanoseconds']
137138
_datetimelike_ops = _field_ops + _object_ops + _bool_ops

0 commit comments

Comments
 (0)