Skip to content

Commit c483440

Browse files
committed
pandas-dev#26065 Fix Type Annotations in pandas.core.arrays
1 parent 22c2b73 commit c483440

File tree

6 files changed

+31
-22
lines changed

6 files changed

+31
-22
lines changed

pandas/core/arrays/array_.py

Lines changed: 2 additions & 2 deletions
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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from datetime import datetime, timedelta
33
import operator
4-
from typing import Any, Sequence, Tuple, Type, Union
4+
from typing import Any, Sequence, Type, Union, cast
55
import warnings
66

77
import numpy as np
@@ -40,6 +40,7 @@
4040

4141

4242
class AttributesMixin(object):
43+
_data = None # type: np.ndarray
4344

4445
@property
4546
def _attributes(self):
@@ -57,7 +58,8 @@ def _get_attributes_dict(self):
5758
return {k: getattr(self, k, None) for k in self._attributes}
5859

5960
@property
60-
def _scalar_type(self) -> Union[Type, Tuple[Type]]:
61+
def _scalar_type(self) -> Union[Type[Period], Type[Timestamp],
62+
Type[Timedelta]]:
6163
"""The scalar associated with this datelike
6264
6365
* PeriodArray : Period
@@ -479,12 +481,13 @@ def __setitem__(
479481
raise ValueError("setting an array element with a sequence.")
480482

481483
if (not is_slice
482-
and len(key) != len(value)
484+
and len(cast(Sequence, key)) != len(value)
483485
and not com.is_bool_indexer(key)):
484486
msg = ("shape mismatch: value array of length '{}' does not "
485487
"match indexing result of length '{}'.")
486-
raise ValueError(msg.format(len(key), len(value)))
487-
if not is_slice and len(key) == 0:
488+
raise ValueError(msg.format(
489+
len(cast(Sequence, key)), len(value)))
490+
if not is_slice and len(cast(Sequence, key)) == 0:
488491
return
489492

490493
value = type(self)._from_sequence(value, dtype=self.dtype)

pandas/core/arrays/integer.py

Lines changed: 3 additions & 2 deletions
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -943,7 +943,7 @@ def mid(self):
943943
else False
944944
"""
945945

946-
@property
946+
@property # type: ignore # Mypy does not support decorated properties
947947
@Appender(_interval_shared_docs['is_non_overlapping_monotonic']
948948
% _shared_docs_kwargs)
949949
def is_non_overlapping_monotonic(self):

pandas/core/arrays/period.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from datetime import timedelta
33
import operator
4-
from typing import Any, Callable, Optional, Sequence, Union
4+
from typing import Any, Callable, List, Optional, Sequence, Union
55

66
import numpy as np
77

@@ -24,7 +24,7 @@
2424
from pandas.core.dtypes.missing import isna, notna
2525

2626
import pandas.core.algorithms as algos
27-
from pandas.core.arrays import ExtensionArray, datetimelike as dtl
27+
from pandas.core.arrays import datetimelike as dtl
2828
import pandas.core.common as com
2929

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

138138
# Names others delegate to us
139-
_other_ops = []
139+
_other_ops = [] # type: List[str]
140140
_bool_ops = ['is_leap_year']
141141
_object_ops = ['start_time', 'end_time', 'freq']
142142
_field_ops = ['year', 'month', 'day', 'hour', 'minute', 'second',
@@ -190,7 +190,8 @@ def _from_sequence(
190190
copy: bool = False,
191191
) -> ABCPeriodArray:
192192
if dtype:
193-
freq = dtype.freq
193+
freq = dtype.freq # type: ignore
194+
# freq is generated dynamically in PeriodDtype's __new__ method
194195
else:
195196
freq = None
196197

@@ -277,7 +278,7 @@ def _check_compatible_with(self, other):
277278
def dtype(self):
278279
return self._dtype
279280

280-
@property
281+
@property # type: ignore # read-only property overwriting read/write
281282
def freq(self):
282283
"""
283284
Return the frequency object for this PeriodArray.
@@ -539,17 +540,20 @@ def _sub_period(self, other):
539540

540541
return new_data
541542

543+
Other_types = Union[ABCPeriodArray, ABCSeries, ABCPeriodIndex,
544+
np.ndarray]
545+
542546
@Appender(dtl.DatetimeLikeArrayMixin._addsub_int_array.__doc__)
543547
def _addsub_int_array(
544548
self,
545-
other: Union[ExtensionArray, np.ndarray, ABCIndexClass],
549+
other: Other_types,
546550
op: Callable[[Any], Any]
547551
) -> ABCPeriodArray:
548552
assert op in [operator.add, operator.sub]
549553
if op is operator.sub:
550554
other = -other
551-
res_values = algos.checked_add_with_arr(self.asi8, other,
552-
arr_mask=self._isnan)
555+
res_values = algos.checked_add_with_arr(self.asi8, other,
556+
arr_mask=self._isnan)
553557
res_values = res_values.view('i8')
554558
res_values[self._isnan] = iNaT
555559
return type(self)(res_values, freq=self.freq)
@@ -782,7 +786,7 @@ def period_array(
782786
data = np.asarray(data)
783787

784788
if freq:
785-
dtype = PeriodDtype(freq)
789+
dtype = PeriodDtype(freq) # type: Optional[PeriodDtype]
786790
else:
787791
dtype = None
788792

pandas/core/arrays/timedeltas.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from datetime import timedelta
33
import textwrap
4+
from typing import List
45
import warnings
56

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

0 commit comments

Comments
 (0)