Skip to content

Commit cabaf80

Browse files
simonjayhawkinsproost
authored andcommitted
TYP: disallow comment-based annotation syntax (pandas-dev#29741)
1 parent e73de82 commit cabaf80

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+209
-194
lines changed

ci/code_checks.sh

+4
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then
194194
invgrep -R --include="*.py" --include="*.pyx" -E 'class.*:\n\n( )+"""' .
195195
RET=$(($RET + $?)) ; echo $MSG "DONE"
196196

197+
MSG='Check for use of comment-based annotation syntax' ; echo $MSG
198+
invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas
199+
RET=$(($RET + $?)) ; echo $MSG "DONE"
200+
197201
MSG='Check that no file in the repo contains trailing whitespaces' ; echo $MSG
198202
set -o pipefail
199203
if [[ "$AZURE" == "true" ]]; then

doc/source/development/contributing.rst

+5-5
Original file line numberDiff line numberDiff line change
@@ -804,27 +804,27 @@ Types imports should follow the ``from typing import ...`` convention. So rather
804804
805805
import typing
806806
807-
primes = [] # type: typing.List[int]
807+
primes: typing.List[int] = []
808808
809809
You should write
810810

811811
.. code-block:: python
812812
813813
from typing import List, Optional, Union
814814
815-
primes = [] # type: List[int]
815+
primes: List[int] = []
816816
817817
``Optional`` should be used where applicable, so instead of
818818

819819
.. code-block:: python
820820
821-
maybe_primes = [] # type: List[Union[int, None]]
821+
maybe_primes: List[Union[int, None]] = []
822822
823823
You should write
824824

825825
.. code-block:: python
826826
827-
maybe_primes = [] # type: List[Optional[int]]
827+
maybe_primes: List[Optional[int]] = []
828828
829829
In some cases in the code base classes may define class variables that shadow builtins. This causes an issue as described in `Mypy 1775 <https://github.com/python/mypy/issues/1775#issuecomment-310969854>`_. The defensive solution here is to create an unambiguous alias of the builtin and use that without your annotation. For example, if you come across a definition like
830830

@@ -840,7 +840,7 @@ The appropriate way to annotate this would be as follows
840840
str_type = str
841841
842842
class SomeClass2:
843-
str = None # type: str_type
843+
str: str_type = None
844844
845845
In some cases you may be tempted to use ``cast`` from the typing module when you know better than the analyzer. This occurs particularly when using custom inference functions. For example
846846

pandas/_config/config.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,16 @@
5858
RegisteredOption = namedtuple("RegisteredOption", "key defval doc validator cb")
5959

6060
# holds deprecated option metdata
61-
_deprecated_options = {} # type: Dict[str, DeprecatedOption]
61+
_deprecated_options: Dict[str, DeprecatedOption] = {}
6262

6363
# holds registered option metdata
64-
_registered_options = {} # type: Dict[str, RegisteredOption]
64+
_registered_options: Dict[str, RegisteredOption] = {}
6565

6666
# holds the current values for registered options
67-
_global_config = {} # type: Dict[str, str]
67+
_global_config: Dict[str, str] = {}
6868

6969
# keys which have a special meaning
70-
_reserved_keys = ["all"] # type: List[str]
70+
_reserved_keys: List[str] = ["all"]
7171

7272

7373
class OptionError(AttributeError, KeyError):

pandas/_version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class NotThisMethod(Exception):
4747
pass
4848

4949

50-
HANDLERS = {} # type: Dict[str, Dict[str, Callable]]
50+
HANDLERS: Dict[str, Dict[str, Callable]] = {}
5151

5252

5353
def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator

pandas/compat/numpy/function.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs):
106106
return skipna
107107

108108

109-
ARGSORT_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Union[int, str]]]
109+
ARGSORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict()
110110
ARGSORT_DEFAULTS["axis"] = -1
111111
ARGSORT_DEFAULTS["kind"] = "quicksort"
112112
ARGSORT_DEFAULTS["order"] = None
@@ -122,7 +122,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs):
122122

123123
# two different signatures of argsort, this second validation
124124
# for when the `kind` param is supported
125-
ARGSORT_DEFAULTS_KIND = OrderedDict() # type: OrderedDict[str, Optional[int]]
125+
ARGSORT_DEFAULTS_KIND: "OrderedDict[str, Optional[int]]" = OrderedDict()
126126
ARGSORT_DEFAULTS_KIND["axis"] = -1
127127
ARGSORT_DEFAULTS_KIND["order"] = None
128128
validate_argsort_kind = CompatValidator(
@@ -169,14 +169,14 @@ def validate_clip_with_axis(axis, args, kwargs):
169169
return axis
170170

171171

172-
COMPRESS_DEFAULTS = OrderedDict() # type: OrderedDict[str, Any]
172+
COMPRESS_DEFAULTS: "OrderedDict[str, Any]" = OrderedDict()
173173
COMPRESS_DEFAULTS["axis"] = None
174174
COMPRESS_DEFAULTS["out"] = None
175175
validate_compress = CompatValidator(
176176
COMPRESS_DEFAULTS, fname="compress", method="both", max_fname_arg_count=1
177177
)
178178

179-
CUM_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Any]
179+
CUM_FUNC_DEFAULTS: "OrderedDict[str, Any]" = OrderedDict()
180180
CUM_FUNC_DEFAULTS["dtype"] = None
181181
CUM_FUNC_DEFAULTS["out"] = None
182182
validate_cum_func = CompatValidator(
@@ -202,7 +202,7 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
202202
return skipna
203203

204204

205-
ALLANY_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[bool]]
205+
ALLANY_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict()
206206
ALLANY_DEFAULTS["dtype"] = None
207207
ALLANY_DEFAULTS["out"] = None
208208
ALLANY_DEFAULTS["keepdims"] = False
@@ -224,28 +224,28 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
224224
MINMAX_DEFAULTS, fname="max", method="both", max_fname_arg_count=1
225225
)
226226

227-
RESHAPE_DEFAULTS = dict(order="C") # type: Dict[str, str]
227+
RESHAPE_DEFAULTS: Dict[str, str] = dict(order="C")
228228
validate_reshape = CompatValidator(
229229
RESHAPE_DEFAULTS, fname="reshape", method="both", max_fname_arg_count=1
230230
)
231231

232-
REPEAT_DEFAULTS = dict(axis=None) # type: Dict[str, Any]
232+
REPEAT_DEFAULTS: Dict[str, Any] = dict(axis=None)
233233
validate_repeat = CompatValidator(
234234
REPEAT_DEFAULTS, fname="repeat", method="both", max_fname_arg_count=1
235235
)
236236

237-
ROUND_DEFAULTS = dict(out=None) # type: Dict[str, Any]
237+
ROUND_DEFAULTS: Dict[str, Any] = dict(out=None)
238238
validate_round = CompatValidator(
239239
ROUND_DEFAULTS, fname="round", method="both", max_fname_arg_count=1
240240
)
241241

242-
SORT_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Union[int, str]]]
242+
SORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict()
243243
SORT_DEFAULTS["axis"] = -1
244244
SORT_DEFAULTS["kind"] = "quicksort"
245245
SORT_DEFAULTS["order"] = None
246246
validate_sort = CompatValidator(SORT_DEFAULTS, fname="sort", method="kwargs")
247247

248-
STAT_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[Any]]
248+
STAT_FUNC_DEFAULTS: "OrderedDict[str, Optional[Any]]" = OrderedDict()
249249
STAT_FUNC_DEFAULTS["dtype"] = None
250250
STAT_FUNC_DEFAULTS["out"] = None
251251

@@ -273,13 +273,13 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
273273
MEDIAN_DEFAULTS, fname="median", method="both", max_fname_arg_count=1
274274
)
275275

276-
STAT_DDOF_FUNC_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[bool]]
276+
STAT_DDOF_FUNC_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict()
277277
STAT_DDOF_FUNC_DEFAULTS["dtype"] = None
278278
STAT_DDOF_FUNC_DEFAULTS["out"] = None
279279
STAT_DDOF_FUNC_DEFAULTS["keepdims"] = False
280280
validate_stat_ddof_func = CompatValidator(STAT_DDOF_FUNC_DEFAULTS, method="kwargs")
281281

282-
TAKE_DEFAULTS = OrderedDict() # type: OrderedDict[str, Optional[str]]
282+
TAKE_DEFAULTS: "OrderedDict[str, Optional[str]]" = OrderedDict()
283283
TAKE_DEFAULTS["out"] = None
284284
TAKE_DEFAULTS["mode"] = "raise"
285285
validate_take = CompatValidator(TAKE_DEFAULTS, fname="take", method="kwargs")

pandas/core/accessor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111

1212

1313
class DirNamesMixin:
14-
_accessors = set() # type: Set[str]
15-
_deprecations = frozenset() # type: FrozenSet[str]
14+
_accessors: Set[str] = set()
15+
_deprecations: FrozenSet[str] = frozenset()
1616

1717
def _dir_deletions(self):
1818
"""

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
from pandas.core.construction import array, extract_array
5151
from pandas.core.indexers import validate_indices
5252

53-
_shared_docs = {} # type: Dict[str, str]
53+
_shared_docs: Dict[str, str] = {}
5454

5555

5656
# --------------- #

pandas/core/apply.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ def frame_apply(
3434
""" construct and return a row or column based frame apply object """
3535

3636
axis = obj._get_axis_number(axis)
37+
klass: Type[FrameApply]
3738
if axis == 0:
38-
klass = FrameRowApply # type: Type[FrameApply]
39+
klass = FrameRowApply
3940
elif axis == 1:
4041
klass = FrameColumnApply
4142

pandas/core/arrays/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
_not_implemented_message = "{} does not implement {}."
3131

32-
_extension_array_shared_docs = dict() # type: Dict[str, str]
32+
_extension_array_shared_docs: Dict[str, str] = dict()
3333

3434

3535
def try_cast_to_ea(cls_or_instance, obj, dtype=None):

pandas/core/arrays/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151

5252

5353
class AttributesMixin:
54-
_data = None # type: np.ndarray
54+
_data: np.ndarray
5555

5656
@classmethod
5757
def _simple_new(cls, values, **kwargs):

pandas/core/arrays/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps
320320
# -----------------------------------------------------------------
321321
# Constructors
322322

323-
_dtype = None # type: Union[np.dtype, DatetimeTZDtype]
323+
_dtype: Union[np.dtype, DatetimeTZDtype]
324324
_freq = None
325325

326326
def __init__(self, values, dtype=_NS_DTYPE, freq=None, copy=False):

pandas/core/arrays/integer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ class _IntegerDtype(ExtensionDtype):
4040
The attributes name & type are set when these subclasses are created.
4141
"""
4242

43-
name = None # type: str
43+
name: str
4444
base = None
45-
type = None # type: Type
45+
type: Type
4646
na_value = np.nan
4747

4848
def __repr__(self) -> str:

pandas/core/arrays/period.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps):
161161
_scalar_type = Period
162162

163163
# Names others delegate to us
164-
_other_ops = [] # type: List[str]
164+
_other_ops: List[str] = []
165165
_bool_ops = ["is_leap_year"]
166166
_object_ops = ["start_time", "end_time", "freq"]
167167
_field_ops = [
@@ -894,9 +894,9 @@ def period_array(
894894

895895
data = np.asarray(data)
896896

897+
dtype: Optional[PeriodDtype]
897898
if freq:
898-
# typed Optional here because the else block below assigns None
899-
dtype = PeriodDtype(freq) # type: Optional[PeriodDtype]
899+
dtype = PeriodDtype(freq)
900900
else:
901901
dtype = None
902902

pandas/core/arrays/timedeltas.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps):
161161
_scalar_type = Timedelta
162162
__array_priority__ = 1000
163163
# define my properties & methods for delegation
164-
_other_ops = [] # type: List[str]
165-
_bool_ops = [] # type: List[str]
164+
_other_ops: List[str] = []
165+
_bool_ops: List[str] = []
166166
_object_ops = ["freq"]
167167
_field_ops = ["days", "seconds", "microseconds", "nanoseconds"]
168168
_datetimelike_ops = _field_ops + _object_ops + _bool_ops

pandas/core/base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
from pandas.core.arrays import ExtensionArray
3737
import pandas.core.nanops as nanops
3838

39-
_shared_docs = dict() # type: Dict[str, str]
39+
_shared_docs: Dict[str, str] = dict()
4040
_indexops_doc_kwargs = dict(
4141
klass="IndexOpsMixin",
4242
inplace="",
@@ -603,7 +603,7 @@ def _is_builtin_func(self, arg):
603603

604604

605605
class ShallowMixin:
606-
_attributes = [] # type: List[str]
606+
_attributes: List[str] = []
607607

608608
def _shallow_copy(self, obj=None, **kwargs):
609609
"""
@@ -627,7 +627,7 @@ class IndexOpsMixin:
627627

628628
# ndarray compatibility
629629
__array_priority__ = 1000
630-
_deprecations = frozenset(
630+
_deprecations: FrozenSet[str] = frozenset(
631631
[
632632
"tolist", # tolist is not deprecated, just suppressed in the __dir__
633633
"base",
@@ -637,7 +637,7 @@ class IndexOpsMixin:
637637
"flags",
638638
"strides",
639639
]
640-
) # type: FrozenSet[str]
640+
)
641641

642642
def transpose(self, *args, **kwargs):
643643
"""

pandas/core/computation/expr.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ class BaseExprVisitor(ast.NodeVisitor):
378378
preparser : callable
379379
"""
380380

381-
const_type = Constant # type: Type[Term]
381+
const_type: Type[Term] = Constant
382382
term_type = Term
383383

384384
binary_ops = _cmp_ops_syms + _bool_ops_syms + _arith_ops_syms

pandas/core/dtypes/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def __from_arrow__(
8181
provided for registering virtual subclasses.
8282
"""
8383

84-
_metadata = () # type: Tuple[str, ...]
84+
_metadata: Tuple[str, ...] = ()
8585

8686
def __str__(self) -> str:
8787
return self.name

0 commit comments

Comments
 (0)