-
Notifications
You must be signed in to change notification settings - Fork 23
/
pyi.py
1289 lines (1091 loc) · 46.7 KB
/
pyi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import ast
import logging
import optparse
import re
import sys
from collections import Counter
from collections.abc import Container, Iterable, Iterator, Sequence
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
from functools import partial
from itertools import chain
from keyword import iskeyword
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, NamedTuple
from flake8 import checker # type: ignore
from flake8.plugins.pyflakes import FlakesChecker # type: ignore
from pyflakes.checker import ( # type: ignore[import]
PY2,
ClassDefinition,
ClassScope,
FunctionScope,
ModuleScope,
)
if sys.version_info >= (3, 9):
from ast import unparse
else:
from ast_decompiler import decompile as unparse
if TYPE_CHECKING:
from typing import TypeGuard
__version__ = "22.1.0"
LOG = logging.getLogger("flake8.pyi")
class Error(NamedTuple):
lineno: int
col: int
message: str
type: type
class TypeVarInfo(NamedTuple):
cls_name: str
name: str
_MAPPING_SLICE = "KeyType, ValueType"
_TYPE_SLICE = "MyClass"
_COUNTER_SLICE = "KeyType"
_CONTEXTLIB_SLICE = "T"
_SET_SLICE = "T"
_SEQUENCE_SLICE = "T"
# ChainMap and AsyncContextManager do not exist in typing or typing_extensions in Python 2,
# so we can disallow importing them from anywhere except collections and contextlib respectively.
_BAD_Y022_IMPORTS = {
# typing aliases for collections
"typing.Counter": ("collections.Counter", _COUNTER_SLICE),
"typing.Deque": ("collections.deque", _SEQUENCE_SLICE),
"typing.DefaultDict": ("collections.defaultdict", _MAPPING_SLICE),
"typing.ChainMap": ("collections.ChainMap", _MAPPING_SLICE),
# typing aliases for builtins
"typing.Dict": ("dict", _MAPPING_SLICE),
"typing.FrozenSet": ("frozenset", _SET_SLICE),
"typing.List": ("list", _SEQUENCE_SLICE),
"typing.Set": ("set", _SET_SLICE),
"typing.Tuple": ("tuple", "Foo, Bar"),
"typing.Type": ("type", _TYPE_SLICE),
# One typing alias for contextlib
"typing.AsyncContextManager": (
"contextlib.AbstractAsyncContextManager",
_CONTEXTLIB_SLICE,
),
# typing_extensions aliases for collections
"typing_extensions.Counter": ("collections.Counter", _COUNTER_SLICE),
"typing_extensions.Deque": ("collections.deque", _SEQUENCE_SLICE),
"typing_extensions.DefaultDict": ("collections.defaultdict", _MAPPING_SLICE),
"typing_extensions.ChainMap": ("collections.ChainMap", _MAPPING_SLICE),
# One typing_extensions alias for a builtin
"typing_extensions.Type": ("type", _TYPE_SLICE),
# one typing_extensions alias for contextlib
"typing_extensions.AsyncContextManager": (
"contextlib.AbstractAsyncContextManager",
_CONTEXTLIB_SLICE,
),
}
# typing_extensions.ContextManager is omitted from the Y023 and Y027 collections - special-cased
# We use `None` to signify that the object shouldn't be parameterised.
_BAD_Y023_IMPORTS = {
# collections.abc aliases
"Awaitable": "T",
"Coroutine": "YieldType, SendType, ReturnType",
"AsyncIterable": "T",
"AsyncIterator": "T",
"AsyncGenerator": "YieldType, SendType",
# typing aliases
"Protocol": None,
"runtime_checkable": None,
"ClassVar": "T",
"NewType": None,
"overload": None,
"Text": None,
"NoReturn": None,
}
_BAD_Y027_IMPORTS = {
"typing.ContextManager": ("contextlib.AbstractContextManager", _CONTEXTLIB_SLICE),
"typing.OrderedDict": ("collections.OrderedDict", _MAPPING_SLICE),
"typing_extensions.OrderedDict": ("collections.OrderedDict", _MAPPING_SLICE),
}
class PyiAwareFlakesChecker(FlakesChecker):
def deferHandleNode(self, node, parent):
self.deferFunction(lambda: self.handleNode(node, parent))
def ASSIGN(self, node) -> None:
"""This is a custom implementation of ASSIGN derived from
handleChildren() in pyflakes 1.3.0.
The point here is that on module level, there's type aliases that we
want to bind eagerly, but defer computation of the values of the
assignments (the type aliases might have forward references).
"""
if not isinstance(self.scope, ModuleScope):
super().ASSIGN(node)
return
for target in node.targets:
self.handleNode(target, node)
self.deferHandleNode(node.value, node)
def ANNASSIGN(self, node) -> None:
"""
Annotated assignments don't have annotations evaluated on function
scope, hence the custom implementation. Compared to the pyflakes
version, we defer evaluation of the annotations (and values on
module level).
"""
if node.value:
# Only bind the *target* if the assignment has value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
if not isinstance(self.scope, FunctionScope):
self.deferHandleNode(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value*...
if isinstance(self.scope, ModuleScope):
# ...later (if module scope).
self.deferHandleNode(node.value, node)
else:
# ...now.
self.handleNode(node.value, node)
def LAMBDA(self, node) -> None:
"""This is likely very brittle, currently works for pyflakes 1.3.0.
Deferring annotation handling depends on the fact that during calls
to LAMBDA visiting the function's body is already deferred and the
only eager calls to `handleNode` are for annotations.
"""
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode # type: ignore[assignment]
super().LAMBDA(node)
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode # type: ignore[assignment]
def CLASSDEF(self, node) -> None:
if not isinstance(self.scope, ModuleScope):
# This shouldn't be necessary because .pyi files don't nest
# scopes much, but better safe than sorry.
super().CLASSDEF(node)
return
# What follows is copied from pyflakes 1.3.0. The only changes are the
# deferHandleNode calls.
for decorator in node.decorator_list:
self.handleNode(decorator, node)
for baseNode in node.bases:
self.deferHandleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.deferHandleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (
self.withDoctest
and not self._in_doctest()
and not isinstance(self.scope, FunctionScope)
):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def handleNodeDelete(self, node) -> None:
"""Null implementation.
Lets users use `del` in stubs to denote private names.
"""
return
class PyiAwareFileChecker(checker.FileChecker):
def run_check(self, plugin, **kwargs):
if self.filename == "-":
filename = self.options.stdin_display_name
else:
filename = self.filename
if filename.endswith(".pyi") and plugin["plugin"] == FlakesChecker:
LOG.info(
"Replacing FlakesChecker with PyiAwareFlakesChecker while "
"checking %r",
filename,
)
plugin = dict(plugin)
plugin["plugin"] = PyiAwareFlakesChecker
return super().run_check(plugin, **kwargs)
class LegacyNormalizer(ast.NodeTransformer):
"""Transform AST to be consistent across Python versions."""
if sys.version_info < (3, 9):
def visit_Index(self, node: ast.Index) -> ast.expr:
"""Index nodes no longer exist in Python 3.9.
For example, consider the AST representing Union[str, int].
Before 3.9: Subscript(value=Name(id='Union'), slice=Index(value=Tuple(...)))
3.9 and newer: Subscript(value=Name(id='Union'), slice=Tuple(...))
"""
return node.value
def _is_name(node: ast.expr | None, name: str) -> bool:
"""Return True if `node` is an `ast.Name` node with id `name`
>>> import ast
>>> node = ast.Name(id="Any")
>>> _is_name(node, "Any")
True
"""
return isinstance(node, ast.Name) and node.id == name
_TYPING_MODULES = frozenset({"typing", "typing_extensions"})
def _is_object(node: ast.expr, name: str, *, from_: Container[str]) -> bool:
"""Determine whether `node` is an ast representation of `name`.
Return True if `node` is either:
1). Of shape `ast.Name(id=<name>)`, or;
2). Of shape `ast.Attribute(value=ast.Name(id=<parent>), attr=<name>)`,
where <parent> is a string that can be found within the `from_` collection of
strings.
>>> import ast
>>> node1 = ast.Name(id="Literal")
>>> node2 = ast.Attribute(value=ast.Name(id="typing"), attr="Literal")
>>> node3 = ast.Attribute(value=ast.Name(id="typing_extensions"), attr="Literal")
>>> from functools import partial
>>> _is_Literal = partial(_is_object, name="Literal", from_=_TYPING_MODULES)
>>> _is_Literal(node1)
True
>>> _is_Literal(node2)
True
>>> _is_Literal(node3)
True
"""
return _is_name(node, name) or (
isinstance(node, ast.Attribute)
and node.attr == name
and isinstance(node.value, ast.Name)
and node.value.id in from_
)
_is_TypeAlias = partial(_is_object, name="TypeAlias", from_=_TYPING_MODULES)
_is_NamedTuple = partial(_is_object, name="NamedTuple", from_={"typing"})
_is_TypedDict = partial(_is_object, name="TypedDict", from_=_TYPING_MODULES)
_is_Literal = partial(_is_object, name="Literal", from_=_TYPING_MODULES)
_is_abstractmethod = partial(_is_object, name="abstractmethod", from_={"abc"})
_is_Any = partial(_is_object, name="Any", from_={"typing"})
_is_overload = partial(_is_object, name="overload", from_={"typing"})
_is_final = partial(_is_object, name="final", from_=_TYPING_MODULES)
_is_Self = partial(_is_object, name="Self", from_=({"_typeshed"} | _TYPING_MODULES))
def _is_decorated_with_final(
node: ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef,
) -> bool:
return any(_is_final(decorator) for decorator in node.decorator_list)
def _get_collections_abc_obj_id(node: ast.expr | None) -> str | None:
"""
If the node represents a subscripted object from collections.abc or typing,
return the name of the object.
Else, return None.
>>> import ast
>>> node1 = ast.parse('AsyncIterator[str]').body[0].value
>>> node2 = ast.parse('typing.AsyncIterator[str]').body[0].value
>>> node3 = ast.parse('typing_extensions.AsyncIterator[str]').body[0].value
>>> node4 = ast.parse('collections.abc.AsyncIterator[str]').body[0].value
>>> node5 = ast.parse('collections.OrderedDict[str, int]').body[0].value
>>> _get_collections_abc_obj_id(node1)
'AsyncIterator'
>>> _get_collections_abc_obj_id(node2)
'AsyncIterator'
>>> _get_collections_abc_obj_id(node3)
'AsyncIterator'
>>> _get_collections_abc_obj_id(node4)
'AsyncIterator'
>>> _get_collections_abc_obj_id(node5) is None
True
"""
if not isinstance(node, ast.Subscript):
return None
subscripted_obj = node.value
if isinstance(subscripted_obj, ast.Name):
return subscripted_obj.id
if not isinstance(subscripted_obj, ast.Attribute):
return None
obj_value, obj_attr = subscripted_obj.value, subscripted_obj.attr
if isinstance(obj_value, ast.Name) and obj_value.id in _TYPING_MODULES:
return obj_attr
if (
isinstance(obj_value, ast.Attribute)
and _is_name(obj_value.value, "collections")
and obj_value.attr == "abc"
):
return obj_attr
return None
_ITER_METHODS = frozenset({("Iterator", "__iter__"), ("AsyncIterator", "__aiter__")})
_INPLACE_BINOP_METHODS = frozenset(
{
"__iadd__",
"__isub__",
"__imul__",
"__imatmul__",
"__itruediv__",
"__ifloordiv__",
"__imod__",
"__ipow__",
"__ilshift__",
"__irshift__",
"__iand__",
"__ixor__",
"__ior__",
}
)
def _has_bad_hardcoded_returns(
method: ast.FunctionDef | ast.AsyncFunctionDef, *, classdef: ast.ClassDef
) -> bool:
"""Return `True` if `function` should be rewritten using `_typeshed.Self`."""
# Much too complex for our purposes to worry about overloaded functions or abstractmethods
if any(
_is_overload(deco) or _is_abstractmethod(deco) for deco in method.decorator_list
):
return False
if not _non_kw_only_args_of(method.args): # weird, but theoretically possible
return False
method_name, returns = method.name, method.returns
if isinstance(method, ast.AsyncFunctionDef):
return (
method_name == "__aenter__"
and _is_name(returns, classdef.name)
and not _is_decorated_with_final(classdef)
)
if method_name in _INPLACE_BINOP_METHODS:
return returns is not None and not _is_Self(returns)
if _is_name(returns, classdef.name):
return method_name in {"__enter__", "__new__"} and not _is_decorated_with_final(
classdef
)
return_obj_name = _get_collections_abc_obj_id(returns)
return (return_obj_name, method_name) in _ITER_METHODS and any(
_get_collections_abc_obj_id(base_node) == return_obj_name
for base_node in classdef.bases
)
def _unparse_assign_node(node: ast.Assign | ast.AnnAssign) -> str:
"""Unparse an Assign node, and remove any newlines in it"""
return unparse(node).replace("\n", "")
def _unparse_func_node(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
"""Unparse a function node, and reformat it to fit on one line."""
return re.sub(r"\s+", " ", unparse(node)).strip()
def _is_list_of_str_nodes(seq: list[ast.expr | None]) -> TypeGuard[list[ast.Str]]:
return all(isinstance(item, ast.Str) for item in seq)
def _is_bad_TypedDict(node: ast.Call) -> bool:
"""Evaluate whether an assignment-based TypedDict should be rewritten using class syntax.
Return `False` if the TypedDict appears as though it may be invalidly defined;
type-checkers will raise an error in that eventuality.
"""
args = node.args
if len(args) != 2:
return False
typed_dict_annotations = args[1]
# The runtime supports many ways of creating a TypedDict,
# e.g. `T = TypeDict('T', [['foo', int], ['bar', str]])`,
# but PEP 589 states that type-checkers are only expected
# to accept a dictionary literal for the second argument.
if not isinstance(typed_dict_annotations, ast.Dict):
return False
typed_dict_fields = typed_dict_annotations.keys
if not _is_list_of_str_nodes(typed_dict_fields):
return False
fieldnames = [field.s for field in typed_dict_fields]
return all(
fieldname.isidentifier() and not iskeyword(fieldname)
for fieldname in fieldnames
)
def _non_kw_only_args_of(args: ast.arguments) -> list[ast.arg]:
"""Return a list containing the pos-only args and pos-or-kwd args of `args`"""
# pos-only args don't exist on 3.7
pos_only_args: list[ast.arg] = getattr(args, "posonlyargs", [])
return pos_only_args + args.args
@dataclass
class NestingCounter:
"""Class to help the PyiVisitor keep track of internal state"""
nesting: int = 0
@contextmanager
def enabled(self) -> Iterator[None]:
self.nesting += 1
try:
yield
finally:
self.nesting -= 1
@property
def active(self) -> bool:
"""Determine whether the level of nesting is currently non-zero"""
return bool(self.nesting)
class PyiVisitor(ast.NodeVisitor):
def __init__(self, filename: Path | None = None) -> None:
self.filename = Path("(none)") if filename is None else filename
self.errors: list[Error] = []
# Mapping of all private TypeVars/ParamSpecs/TypeVarTuples to the nodes where they're defined
self.typevarlike_defs: dict[TypeVarInfo, ast.Assign] = {}
# Mapping of each name in the file to the no. of occurrences
self.all_name_occurrences: Counter[str] = Counter()
self.string_literals_allowed = NestingCounter()
self.in_function = NestingCounter()
self.in_class = NestingCounter()
# This is only relevant for visiting classes
self.current_class_node: ast.ClassDef | None = None
def __repr__(self) -> str:
return f"{self.__class__.__name__}(filename={self.filename!r})"
def _check_import_or_attribute(
self, node: ast.Attribute | ast.ImportFrom, module_name: str, object_name: str
) -> None:
fullname = f"{module_name}.{object_name}"
# Y022 errors
if fullname in _BAD_Y022_IMPORTS:
good_cls_name, params = _BAD_Y022_IMPORTS[fullname]
error_message = Y022.format(
good_syntax=f'"{good_cls_name}[{params}]"',
bad_syntax=f'"{fullname}[{params}]"',
)
# Y027 errors
elif fullname in _BAD_Y027_IMPORTS:
good_cls_name, params = _BAD_Y027_IMPORTS[fullname]
error_message = Y027.format(
good_syntax=f'"{good_cls_name}[{params}]"',
bad_syntax=f'"{fullname}[{params}]"',
)
# Y023 errors
elif module_name == "typing_extensions":
if object_name in _BAD_Y023_IMPORTS:
slice_contents = _BAD_Y023_IMPORTS[object_name]
params = "" if slice_contents is None else f"[{slice_contents}]"
error_message = Y023.format(
good_syntax=f'"typing.{object_name}{params}"',
bad_syntax=f'"typing_extensions.{object_name}{params}"',
)
elif object_name == "ContextManager":
suggested_syntax = (
f'"contextlib.AbstractContextManager[{_CONTEXTLIB_SLICE}]" '
f'(or "typing.ContextManager[{_CONTEXTLIB_SLICE}]" '
f"in Python 2-compatible code)"
)
error_message = Y023.format(
good_syntax=suggested_syntax,
bad_syntax=f'"typing_extensions.ContextManager[{_CONTEXTLIB_SLICE}]"',
)
error_message += " (PEP 585 syntax)"
else:
return
# Y024 errors
elif fullname == "collections.namedtuple":
error_message = Y024
else:
return
self.error(node, error_message)
def visit_Attribute(self, node: ast.Attribute) -> None:
self.generic_visit(node)
thing = node.value
if not isinstance(thing, ast.Name):
return
self._check_import_or_attribute(
node=node, module_name=thing.id, object_name=node.attr
)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
module_name, imported_objects = node.module, node.names
if module_name is None:
return
if module_name == "collections.abc" and any(
obj.name == "Set" and obj.asname != "AbstractSet"
for obj in imported_objects
):
return self.error(node, Y025)
for obj in imported_objects:
self._check_import_or_attribute(
node=node, module_name=module_name, object_name=obj.name
)
def _check_assignment_to_function(
self, node: ast.Assign, function: ast.expr, object_name: str
) -> None:
"""Attempt to find assignments to TypeVar-like objects.
TypeVars should usually be private.
If they are private, they should be used at least once in the file in which they are defined.
"""
if isinstance(function, ast.Name):
cls_name = function.id
elif (
isinstance(function, ast.Attribute)
and isinstance(function.value, ast.Name)
and function.value.id in _TYPING_MODULES
):
cls_name = function.attr
else:
return
if cls_name in {"TypeVar", "ParamSpec", "TypeVarTuple"}:
if object_name.startswith("_"):
target_info = TypeVarInfo(cls_name=cls_name, name=object_name)
self.typevarlike_defs[target_info] = node
else:
self.error(node, Y001.format(cls_name))
def visit_Assign(self, node: ast.Assign) -> None:
if self.in_function.active:
# We error for unexpected things within functions separately.
self.generic_visit(node)
return
if len(node.targets) == 1:
target = node.targets[0]
if isinstance(target, ast.Name):
target_name = target.id
else:
self.error(node, Y017)
target_name = None
else:
self.error(node, Y017)
target_name = None
if target_name == "__all__":
with self.string_literals_allowed.enabled():
self.generic_visit(node)
else:
self.generic_visit(node)
if target_name is None:
return
assignment = node.value
if isinstance(assignment, ast.Call):
self._check_assignment_to_function(
node=node, function=assignment.func, object_name=target_name
)
elif isinstance(assignment, (ast.Num, ast.Str, ast.Bytes)):
return self._Y015_error(node)
if (
isinstance(assignment, (ast.Constant, ast.NameConstant))
and not isinstance(assignment, ast.Ellipsis)
and assignment.value is not None
):
return self._Y015_error(node)
# We avoid triggering Y026 for calls and = ... because there are various
# unusual cases where assignment to the result of a call is legitimate
# in stubs.
if target_name != "__all__" and not isinstance(
assignment, (ast.Ellipsis, ast.Call)
):
self.error(node, Y026)
def visit_Name(self, node: ast.Name) -> None:
self.all_name_occurrences[node.id] += 1
def visit_Call(self, node: ast.Call) -> None:
function = node.func
self.visit(function)
if _is_NamedTuple(function):
return self.error(node, Y028)
elif _is_TypedDict(function):
if _is_bad_TypedDict(node):
self.error(node, Y031)
return
# String literals can appear in positional arguments for
# TypeVar definitions.
with self.string_literals_allowed.enabled():
for arg in node.args:
self.visit(arg)
# But in keyword arguments they're most likely TypeVar bounds,
# which should not be quoted.
for kw in node.keywords:
self.visit(kw)
# 3.8+
def visit_Constant(self, node: ast.Constant) -> None:
if not self.string_literals_allowed.active and isinstance(node.value, str):
self.error(node, Y020)
# 3.7 and lower
def visit_Str(self, node: ast.Str) -> None:
if not self.string_literals_allowed.active:
self.error(node, Y020)
def visit_Expr(self, node: ast.Expr) -> None:
if isinstance(node.value, ast.Str):
self.error(node, Y021)
else:
self.generic_visit(node)
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
if _is_name(node.target, "__all__") and not self.in_class.active:
with self.string_literals_allowed.enabled():
self.generic_visit(node)
if node.value is None:
self.error(node, Y035)
return
self.generic_visit(node)
if _is_TypeAlias(node.annotation):
return
if node.value and not isinstance(node.value, ast.Ellipsis):
self._Y015_error(node)
def _check_union_members(self, members: Sequence[ast.expr]) -> None:
members_by_dump: dict[str, list[ast.expr]] = {}
for member in members:
members_by_dump.setdefault(ast.dump(member), []).append(member)
dupes_in_union = False
for member_list in members_by_dump.values():
if len(member_list) >= 2:
self.error(member_list[1], Y016.format(unparse(member_list[1])))
dupes_in_union = True
if not dupes_in_union:
self._check_for_multiple_literals(members)
def _check_for_multiple_literals(self, members: Sequence[ast.expr]) -> None:
literals_in_union, non_literals_in_union = [], []
for member in members:
if isinstance(member, ast.Subscript) and _is_Literal(member.value):
literals_in_union.append(member.slice)
else:
non_literals_in_union.append(member)
if len(literals_in_union) < 2:
return
new_literal_members: list[ast.expr] = []
for literal in literals_in_union:
if isinstance(literal, ast.Tuple):
new_literal_members.extend(literal.elts)
else:
new_literal_members.append(literal)
new_literal_slice = unparse(ast.Tuple(new_literal_members)).strip("()")
if non_literals_in_union:
suggestion = f'Combine them into one, e.g. "Literal[{new_literal_slice}]".'
else:
suggestion = f'Use a single Literal, e.g. "Literal[{new_literal_slice}]".'
self.error(members[0], Y030.format(suggestion=suggestion))
def visit_BinOp(self, node: ast.BinOp) -> None:
if not isinstance(node.op, ast.BitOr):
self.generic_visit(node)
return
# str|int|None parses as BinOp(BinOp(str, |, int), |, None)
current: ast.expr = node
members = []
while isinstance(current, ast.BinOp) and isinstance(current.op, ast.BitOr):
members.append(current.right)
current = current.left
members.append(current)
members.reverse()
# Do not call generic_visit(node), that would call this method again unnecessarily
for member in members:
self.visit(member)
self._check_union_members(members)
def visit_Subscript(self, node: ast.Subscript) -> None:
subscripted_object = node.value
if isinstance(subscripted_object, ast.Name):
subscripted_object_name = subscripted_object.id
elif (
isinstance(subscripted_object, ast.Attribute)
and isinstance(subscripted_object.value, ast.Name)
and subscripted_object.value.id in _TYPING_MODULES
):
subscripted_object_name = subscripted_object.attr
else:
subscripted_object_name = None
self.visit(subscripted_object)
if subscripted_object_name == "Literal":
with self.string_literals_allowed.enabled():
self.visit(node.slice)
return
if isinstance(node.slice, ast.Tuple):
self._visit_slice_tuple(node.slice, subscripted_object_name)
else:
self.visit(node.slice)
def _visit_slice_tuple(self, node: ast.Tuple, parent: str | None) -> None:
if parent == "Union":
self._check_union_members(node.elts)
self.visit(node)
elif parent == "Annotated":
# Allow literals, except in the first argument
if len(node.elts) > 1:
self.visit(node.elts[0])
with self.string_literals_allowed.enabled():
for elt in node.elts[1:]:
self.visit(elt)
else:
self.visit(node)
else:
self.visit(node)
def visit_If(self, node: ast.If) -> None:
# No types can appear in if conditions, so avoid confusing additional errors.
with self.string_literals_allowed.enabled():
self.generic_visit(node)
test = node.test
if isinstance(test, ast.BoolOp):
for expression in test.values:
self._check_if_expression(expression)
else:
self._check_if_expression(test)
def _check_if_expression(self, node: ast.expr) -> None:
if not isinstance(node, ast.Compare):
self.error(node, Y002)
return
if len(node.comparators) != 1:
# mypy doesn't support chained comparisons
self.error(node, Y002)
return
if isinstance(node.left, ast.Subscript):
self._check_subscript_version_check(node)
elif isinstance(node.left, ast.Attribute):
if _is_name(node.left.value, "sys"):
if node.left.attr == "platform":
self._check_platform_check(node)
elif node.left.attr == "version_info":
self._check_version_check(node)
else:
self.error(node, Y002)
else:
self.error(node, Y002)
else:
self.error(node, Y002)
def _check_subscript_version_check(self, node: ast.Compare) -> None:
# unless this is on, comparisons against a single integer aren't allowed
must_be_single = False
# if strict equality is allowed, it must be against a tuple of this length
can_have_strict_equals: int | None = None
version_info = node.left
if isinstance(version_info, ast.Subscript):
slc = version_info.slice
# TODO: ast.Num works, but is deprecated
if isinstance(slc, ast.Num):
# anything other than the integer 0 doesn't make much sense
if isinstance(slc.n, int) and slc.n == 0:
must_be_single = True
else:
self.error(node, Y003)
return
elif isinstance(slc, ast.Slice):
if slc.lower is not None or slc.step is not None:
self.error(node, Y003)
return
elif (
# allow only [:1] and [:2]
isinstance(slc.upper, ast.Num)
and isinstance(slc.upper.n, int)
and slc.upper.n in (1, 2)
):
can_have_strict_equals = slc.upper.n
else:
self.error(node, Y003)
return
else:
# extended slicing
self.error(node, Y003)
return
self._check_version_check(
node,
must_be_single=must_be_single,
can_have_strict_equals=can_have_strict_equals,
)
def _check_version_check(
self,
node: ast.Compare,
*,
must_be_single: bool = False,
can_have_strict_equals: int | None = None,
) -> None:
comparator = node.comparators[0]
if must_be_single:
if not isinstance(comparator, ast.Num) or not isinstance(comparator.n, int):
self.error(node, Y003)
elif not isinstance(comparator, ast.Tuple):
self.error(node, Y003)
else:
if not all(isinstance(elt, ast.Num) for elt in comparator.elts):
self.error(node, Y003)
elif len(comparator.elts) > 2:
# mypy only supports major and minor version checks
self.error(node, Y004)
cmpop = node.ops[0]
if isinstance(cmpop, (ast.Lt, ast.GtE)):
pass
elif isinstance(cmpop, (ast.Eq, ast.NotEq)):
if can_have_strict_equals is not None:
if len(comparator.elts) != can_have_strict_equals:
self.error(node, Y005.format(n=can_have_strict_equals))
else:
self.error(node, Y006)
else:
self.error(node, Y006)
def _check_platform_check(self, node: ast.Compare) -> None:
cmpop = node.ops[0]
# "in" might also make sense but we don't currently have one
if not isinstance(cmpop, (ast.Eq, ast.NotEq)):
self.error(node, Y007)
return
comparator = node.comparators[0]
if isinstance(comparator, ast.Str):
# other values are possible but we don't need them right now
# this protects against typos
if comparator.s not in ("linux", "win32", "cygwin", "darwin"):
self.error(node, Y008.format(platform=comparator.s))
else:
self.error(node, Y007)
def visit_ClassDef(self, node: ast.ClassDef) -> None:
old_class_node = self.current_class_node
self.current_class_node = node
with self.in_class.enabled():
self.generic_visit(node)
self.current_class_node = old_class_node
# empty class body should contain "..." not "pass"
if len(node.body) == 1:
statement = node.body[0]
if isinstance(statement, ast.Expr) and isinstance(
statement.value, ast.Ellipsis
):
return
elif isinstance(statement, ast.Pass):
self.error(statement, Y009)
return
for statement in node.body:
# "pass" should not used in class body
if isinstance(statement, ast.Pass):
self.error(statement, Y012)
# "..." should not be used in non-empty class body
elif isinstance(statement, ast.Expr) and isinstance(
statement.value, ast.Ellipsis
):
self.error(statement, Y013)
def _Y034_error(
self, node: ast.FunctionDef | ast.AsyncFunctionDef, cls_name: str
) -> None:
method_name = node.name
copied_node = deepcopy(node)
copied_node.decorator_list.clear()
copied_node.returns = ast.Name(id="Self")
first_arg = _non_kw_only_args_of(copied_node.args)[0]
if method_name == "__new__":
first_arg.annotation = ast.Subscript(
value=ast.Name(id="type"), slice=ast.Name(id="Self")
)
referrer = '"__new__" methods'
else:
first_arg.annotation = ast.Name(id="Self")
referrer = f'"{method_name}" methods in classes like "{cls_name}"'
error_message = Y034.format(
methods=referrer,
method_name=f"{cls_name}.{method_name}",
suggested_syntax=_unparse_func_node(copied_node),
)
self.error(node, error_message)
def _visit_synchronous_method(self, node: ast.FunctionDef) -> None:
method_name = node.name
all_args = node.args
classdef = self.current_class_node
assert classdef is not None
if _has_bad_hardcoded_returns(node, classdef=classdef):
return self._Y034_error(node=node, cls_name=classdef.name)
if all_args.kwonlyargs:
return
non_kw_only_args = _non_kw_only_args_of(all_args)
# Raise an error for defining __str__ or __repr__ on a class, but only if:
# 1). The method is not decorated with @abstractmethod
# 2). The method has the exact same signature as object.__str__/object.__repr__