-
Notifications
You must be signed in to change notification settings - Fork 23
/
pyi.py
2442 lines (2107 loc) · 90.8 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 re
import sys
from collections import Counter, defaultdict
from collections.abc import Container, Iterable, Iterator, Sequence, Set as AbstractSet
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
from functools import cached_property, partial
from itertools import chain, groupby, zip_longest
from keyword import iskeyword
from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, Protocol
from flake8 import checker
from flake8.options.manager import OptionManager
from flake8.plugins.finder import LoadedPlugin
from flake8.plugins.pyflakes import FlakesChecker
from pyflakes.checker import ModuleScope
if TYPE_CHECKING:
# We don't have typing_extensions as a runtime dependency,
# but all our annotations are stringized due to __future__ annotations,
# and mypy thinks typing_extensions is part of the stdlib.
from typing_extensions import TypeAlias, TypeGuard
LOG = logging.getLogger("flake8.pyi")
if sys.version_info >= (3, 12):
_TypeAliasNodeType: TypeAlias = ast.TypeAlias | ast.AnnAssign
else:
_TypeAliasNodeType: TypeAlias = ast.AnnAssign
class Error(NamedTuple):
lineno: int
col: int
message: str
type: type[PyiTreeChecker]
class TypeVarInfo(NamedTuple):
cls_name: str
name: str
class NodeWithLocation(Protocol):
lineno: int
col_offset: int
def all_equal(iterable: Iterable[object]) -> bool:
"""Returns True if all the elements are equal to each other.
Adapted from the CPython itertools documentation.
"""
g = groupby(iterable)
next(g, True)
return not next(g, False)
_MAPPING_SLICE = "KeyType, ValueType"
# Y022: Use stdlib imports instead of aliases from typing/typing_extensions
_BAD_Y022_IMPORTS: dict[str, tuple[str, str | None]] = {
# Aliases for collections
"Counter": ("collections.Counter", "KeyType"),
"Deque": ("collections.deque", "T"),
"DefaultDict": ("collections.defaultdict", _MAPPING_SLICE),
"ChainMap": ("collections.ChainMap", _MAPPING_SLICE),
"OrderedDict": ("collections.OrderedDict", _MAPPING_SLICE),
# Aliases for builtins
"Dict": ("dict", _MAPPING_SLICE),
"FrozenSet": ("frozenset", "T"),
"List": ("list", "T"),
"Set": ("set", "T"),
"Tuple": ("tuple", "Foo, Bar"),
"Type": ("type", "MyClass"),
# Aliases for contextlib
"ContextManager": ("contextlib.AbstractContextManager", "T"),
"AsyncContextManager": ("contextlib.AbstractAsyncContextManager", "T"),
# Aliases for re
"Match": ("re.Match", "T"),
"Pattern": ("re.Pattern", "T"),
# Aliases for collections.abc
# AbstractSet and ByteString are deliberately omitted
# (special-cased elsewhere).
# If the second element of the tuple is `None`,
# it signals that the object shouldn't be parameterized
"Collection": ("collections.abc.Collection", "T"),
"ItemsView": ("collections.abc.ItemsView", _MAPPING_SLICE),
"KeysView": ("collections.abc.KeysView", "KeyType"),
"Mapping": ("collections.abc.Mapping", _MAPPING_SLICE),
"MappingView": ("collections.abc.MappingView", None),
"MutableMapping": ("collections.abc.MutableMapping", _MAPPING_SLICE),
"MutableSequence": ("collections.abc.MutableSequence", "T"),
"MutableSet": ("collections.abc.MutableSet", "T"),
"Sequence": ("collections.abc.Sequence", "T"),
"ValuesView": ("collections.abc.ValuesView", "ValueType"),
"Iterable": ("collections.abc.Iterable", "T"),
"Iterator": ("collections.abc.Iterator", "T"),
"Generator": ("collections.abc.Generator", "YieldType, SendType, ReturnType"),
"Hashable": ("collections.abc.Hashable", None),
"Reversible": ("collections.abc.Reversible", "T"),
"Sized": ("collections.abc.Sized", None),
"Coroutine": ("collections.abc.Coroutine", "YieldType, SendType, ReturnType"),
"AsyncGenerator": ("collections.abc.AsyncGenerator", "YieldType, SendType"),
"AsyncIterator": ("collections.abc.AsyncIterator", "T"),
"AsyncIterable": ("collections.abc.AsyncIterable", "T"),
"Awaitable": ("collections.abc.Awaitable", "T"),
"Callable": ("collections.abc.Callable", None),
"Container": ("collections.abc.Container", "T"),
}
# Y023: Import things from typing instead of typing_extensions
# if they're available from the typing module on 3.8+
_BAD_TYPINGEXTENSIONS_Y023_IMPORTS = frozenset(
{
"Any",
"AnyStr",
"BinaryIO",
"Final",
"ForwardRef",
"Generic",
"IO",
"Literal",
"Protocol",
"TextIO",
"runtime_checkable",
"NewType",
"SupportsAbs",
"SupportsComplex",
"SupportsFloat",
"SupportsIndex",
"SupportsInt",
"SupportsRound",
"TypedDict",
"final",
"overload",
"NoReturn",
# ClassVar deliberately omitted,
# as it's the only one in this group that should be parameterised.
# It is special-cased elsewhere.
#
# Text/Optional/Union are also deliberately omitted,
# as well as the various stdlib aliases in typing(_extensions),
# as you shouldn't be importing them from anywhere! (Y039)
}
)
class PyflakesPreProcessor(ast.NodeTransformer):
"""Transform AST prior to passing it to pyflakes.
This reduces false positives on recursive class definitions.
"""
def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
self.generic_visit(node)
node.bases = [
# Remove the subscript to prevent F821 errors from being emitted
# for (valid) recursive definitions: Foo[Bar] --> Foo
base.value if isinstance(base, ast.Subscript) else base
for base in node.bases
]
return node
class PyiAwareFlakesChecker(FlakesChecker):
def __init__(self, tree: ast.AST, *args: Any, **kwargs: Any) -> None:
super().__init__(PyflakesPreProcessor().visit(tree), *args, **kwargs)
@property
def annotationsFutureEnabled(self) -> Literal[True]:
"""Always allow forward references in `.pyi` files.
Pyflakes can already handle forward refs for annotations,
but only via `from __future__ import annotations`.
In a stub file, `from __future__ import annotations` is unnecessary,
so we pretend to pyflakes that it's always present when linting a `.pyi` file.
"""
return True
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value: bool) -> None:
"""Does nothing, as we always want this property to be `True`."""
def ASSIGN(
self, tree: ast.Assign, omit: str | tuple[str, ...] | None = None
) -> None:
"""Defer evaluation of assignments in the module scope.
This is a custom implementation of ASSIGN, originally derived from
handleChildren() in pyflakes 1.3.0.
This reduces false positives for:
- TypeVars bound or constrained to forward references
- Assignments to forward references that are not explicitly
demarcated as type aliases.
"""
if not isinstance(self.scope, ModuleScope):
super().ASSIGN(tree)
return
for target in tree.targets:
self.handleNode(target, tree)
self.deferFunction(lambda: self.handleNode(tree.value, tree))
def handleNodeDelete(self, node: ast.AST) -> None:
"""Null implementation.
Lets users use `del` in stubs to denote private names.
"""
return
class PyiAwareFileChecker(checker.FileChecker):
def run_check(self, plugin: LoadedPlugin, **kwargs: Any) -> Any:
if plugin.obj is FlakesChecker:
if self.filename == "-":
filename = self.options.stdin_display_name
else:
filename = self.filename
if filename.endswith(".pyi"):
LOG.info(
f"Replacing FlakesChecker with PyiAwareFlakesChecker while "
f"checking {filename!r}"
)
plugin = plugin._replace(obj=PyiAwareFlakesChecker)
return super().run_check(plugin, **kwargs)
def _ast_node_for(string: str) -> ast.AST:
"""Helper function for doctests."""
expr = ast.parse(string).body[0]
assert isinstance(expr, ast.Expr)
return expr.value
def _is_name(node: ast.AST | None, name: str) -> bool:
"""Return True if `node` is an `ast.Name` node with id `name`.
>>> 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"})
_TYPING_OR_COLLECTIONS_ABC = _TYPING_MODULES | {"collections.abc"}
def _is_object(node: ast.AST | None, 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.
>>> _is_AsyncIterator = partial(_is_object, name="AsyncIterator", from_=_TYPING_OR_COLLECTIONS_ABC)
>>> _is_AsyncIterator(_ast_node_for("AsyncIterator"))
True
>>> _is_AsyncIterator(_ast_node_for("typing.AsyncIterator"))
True
>>> _is_AsyncIterator(_ast_node_for("typing_extensions.AsyncIterator"))
True
>>> _is_AsyncIterator(_ast_node_for("collections.abc.AsyncIterator"))
True
"""
if _is_name(node, name):
return True
if not (isinstance(node, ast.Attribute) and node.attr == name):
return False
node_value = node.value
if isinstance(node_value, ast.Name):
return node_value.id in from_
return (
isinstance(node_value, ast.Attribute)
and isinstance(node_value.value, ast.Name)
and f"{node_value.value.id}.{node_value.attr}" in from_
)
_is_BaseException = partial(_is_object, name="BaseException", from_={"builtins"})
_is_TypeAlias = partial(_is_object, name="TypeAlias", from_=_TYPING_MODULES)
_is_NamedTuple = partial(_is_object, name="NamedTuple", from_=_TYPING_MODULES)
_is_deprecated = partial(
_is_object, name="deprecated", from_={"typing_extensions", "warnings"}
)
_is_TypedDict = partial(
_is_object, name="TypedDict", from_=_TYPING_MODULES | {"mypy_extensions"}
)
_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_MODULES)
_is_overload = partial(_is_object, name="overload", from_=_TYPING_MODULES)
_is_final = partial(_is_object, name="final", from_=_TYPING_MODULES)
_is_Self = partial(_is_object, name="Self", from_=({"_typeshed"} | _TYPING_MODULES))
_is_TracebackType = partial(_is_object, name="TracebackType", from_={"types"})
_is_builtins_object = partial(_is_object, name="object", from_={"builtins"})
_is_builtins_type = partial(_is_object, name="type", from_={"builtins"})
_is_Unused = partial(_is_object, name="Unused", from_={"_typeshed"})
_is_Incomplete = partial(_is_object, name="Incomplete", from_={"_typeshed"})
_is_Iterable = partial(_is_object, name="Iterable", from_=_TYPING_OR_COLLECTIONS_ABC)
_is_AsyncIterable = partial(
_is_object, name="AsyncIterable", from_=_TYPING_OR_COLLECTIONS_ABC
)
_is_Protocol = partial(_is_object, name="Protocol", from_=_TYPING_MODULES)
_is_NoReturn = partial(_is_object, name="NoReturn", from_=_TYPING_MODULES)
_is_Final = partial(_is_object, name="Final", from_=_TYPING_MODULES)
_is_Generator = partial(_is_object, name="Generator", from_=_TYPING_OR_COLLECTIONS_ABC)
_is_AsyncGenerator = partial(
_is_object, name="AsyncGenerator", from_=_TYPING_OR_COLLECTIONS_ABC
)
_is_Generic = partial(_is_object, name="Generic", from_=_TYPING_MODULES)
_is_Unpack = partial(_is_object, name="Unpack", from_=_TYPING_MODULES)
def _is_object_or_Unused(node: ast.expr | None) -> bool:
return _is_builtins_object(node) or _is_Unused(node)
def _get_name_of_class_if_from_modules(
classnode: ast.expr, *, modules: Container[str]
) -> str | None:
"""
If `classnode` is an `ast.Name`, return `classnode.id`.
If it's an `ast.Attribute`,check that the part before the dot
is a module in `modules`.
If it is, return the part after the dot; if it isn't, return `None`.
If `classnode` is anything else, return `None`.
>>> _get_name_of_class_if_from_modules(_ast_node_for('int'), modules={'builtins'})
'int'
>>> int_node = _ast_node_for('builtins.int')
>>> _get_name_of_class_if_from_modules(int_node, modules={'builtins'})
'int'
>>> _get_name_of_class_if_from_modules(int_node, modules={'typing'}) is None
True
"""
if isinstance(classnode, ast.Name):
return classnode.id
if isinstance(classnode, ast.Attribute):
module_node = classnode.value
if isinstance(module_node, ast.Name) and module_node.id in modules:
return classnode.attr
if (
isinstance(module_node, ast.Attribute)
and isinstance(module_node.value, ast.Name)
and f"{module_node.value.id}.{module_node.attr}" in modules
):
return classnode.attr
return None
def _is_type_or_Type(node: ast.expr) -> bool:
"""
>>> _is_type_or_Type(_ast_node_for('type'))
True
>>> _is_type_or_Type(_ast_node_for('Type'))
True
>>> _is_type_or_Type(_ast_node_for('builtins.type'))
True
>>> _is_type_or_Type(_ast_node_for('typing_extensions.Type'))
True
>>> _is_type_or_Type(_ast_node_for('typing.Type'))
True
"""
cls_name = _get_name_of_class_if_from_modules(
node, modules=_TYPING_MODULES | {"builtins"}
)
return cls_name in {"type", "Type"}
def _is_None(node: ast.expr) -> bool:
return isinstance(node, ast.Constant) and node.value is None
class ExitArgAnalysis(NamedTuple):
is_union_with_None: bool
non_None_part: ast.expr | None
def __repr__(self) -> str:
if self.non_None_part is None:
non_None_part_repr = "None"
else:
non_None_part_repr = ast.dump(self.non_None_part)
return (
f"ExitArgAnalysis("
f"is_union_with_None={self.is_union_with_None}, "
f"non_None_part={non_None_part_repr}"
f")"
)
def _analyse_exit_method_arg(node: ast.BinOp) -> ExitArgAnalysis:
"""Return a two-item tuple analysing the annotation of an exit-method arg.
The `node` represents a union type written as `X | Y`.
>>> _analyse_exit_method_arg(_ast_node_for('int | str'))
ExitArgAnalysis(is_union_with_None=False, non_None_part=None)
>>> _analyse_exit_method_arg(_ast_node_for('int | None'))
ExitArgAnalysis(is_union_with_None=True, non_None_part=Name(id='int', ctx=Load()))
>>> _analyse_exit_method_arg(_ast_node_for('None | str'))
ExitArgAnalysis(is_union_with_None=True, non_None_part=Name(id='str', ctx=Load()))
"""
assert isinstance(node.op, ast.BitOr)
if _is_None(node.left):
return ExitArgAnalysis(is_union_with_None=True, non_None_part=node.right)
if _is_None(node.right):
return ExitArgAnalysis(is_union_with_None=True, non_None_part=node.left)
return ExitArgAnalysis(is_union_with_None=False, non_None_part=None)
_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, *, class_ctx: EnclosingClassContext
) -> bool:
"""Return `True` if `function` should be rewritten with `typing_extensions.Self`."""
# PEP 673 forbids the use of `typing(_extensions).Self` in metaclasses.
# Do our best to avoid false positives here:
if class_ctx.is_metaclass:
return False
# 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
# weird, but theoretically possible
if not method.args.posonlyargs and not method.args.args:
return False
method_name, returns = method.name, method.returns
if isinstance(method, ast.AsyncFunctionDef):
return (
method_name == "__aenter__"
and _is_name(returns, class_ctx.cls_name)
and not class_ctx.is_decorated_with_final
)
if method_name in _INPLACE_BINOP_METHODS:
return returns is not None and not _is_Self(returns)
if _is_name(returns, class_ctx.cls_name):
return (
method_name in {"__enter__", "__new__"}
and not class_ctx.is_decorated_with_final
)
if isinstance(returns, ast.Subscript):
return_obj_name = _get_name_of_class_if_from_modules(
returns.value, modules=_TYPING_OR_COLLECTIONS_ABC
)
if method_name == "__iter__":
bad_returns = {"Iterable", "Iterator"}
return return_obj_name in bad_returns and class_ctx.contains_in_bases(
"Iterator", from_=_TYPING_OR_COLLECTIONS_ABC
)
elif method_name == "__aiter__":
bad_returns = {"AsyncIterable", "AsyncIterator"}
return return_obj_name in bad_returns and class_ctx.contains_in_bases(
"AsyncIterator", from_=_TYPING_OR_COLLECTIONS_ABC
)
return False
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+", " ", ast.unparse(node))
def _is_list_of_str_nodes(seq: list[ast.expr | None]) -> TypeGuard[list[ast.Constant]]:
return all(
isinstance(item, ast.Constant) and type(item.value) is str for item in seq
)
def _is_bad_TypedDict(node: ast.Call) -> bool:
"""Should the assignment-based TypedDict `node` 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.value for field in typed_dict_fields]
return all(
fieldname.isidentifier() and not iskeyword(fieldname)
for fieldname in fieldnames
)
def _is_assignment_which_must_have_a_value(
target_name: str | None, *, in_class: bool
) -> bool:
return (target_name in {"__match_args__", "__slots__"} and in_class) or (
target_name == "__all__" and not in_class
)
class UnionAnalysis(NamedTuple):
members_by_dump: defaultdict[str, list[ast.expr]]
dupes_in_union: bool
builtins_classes_in_union: set[str]
multiple_literals_in_union: bool
non_literals_in_union: bool
combined_literal_members: list[ast.expr]
# type subscript == type[Foo]
multiple_type_subscripts_in_union: bool
combined_type_subscripts: list[ast.expr]
def _analyse_union(members: Sequence[ast.expr]) -> UnionAnalysis:
"""Return a tuple providing analysis of a given sequence of union members.
>>> source = 'Union[int, memoryview, memoryview, Literal["foo"], Literal[1], type[float], type[str]]'
>>> union = _ast_node_for(source)
>>> analysis = _analyse_union(union.slice.elts)
>>> len(analysis.members_by_dump["Name(id='memoryview', ctx=Load())"])
2
>>> analysis.dupes_in_union
True
>>> "int" in analysis.builtins_classes_in_union
True
>>> "float" in analysis.builtins_classes_in_union
False
>>> analysis.multiple_literals_in_union
True
>>> analysis.non_literals_in_union
True
>>> ast.unparse(ast.Tuple(analysis.combined_literal_members))
"('foo', 1)"
>>> analysis.multiple_type_subscripts_in_union
True
>>> ast.unparse(ast.Tuple(analysis.combined_type_subscripts))
'(float, str)'
"""
non_literals_in_union = False
members_by_dump: defaultdict[str, list[ast.expr]] = defaultdict(list)
builtins_classes_in_union: set[str] = set()
literals_in_union = []
combined_literal_members: list[ast.expr] = []
type_subscripts_in_union: list[ast.expr] = []
for member in members:
members_by_dump[ast.dump(member)].append(member)
name_if_builtins_cls = _get_name_of_class_if_from_modules(
member, modules={"builtins"}
)
if name_if_builtins_cls is not None:
builtins_classes_in_union.add(name_if_builtins_cls)
if isinstance(member, ast.Subscript) and _is_Literal(member.value):
literals_in_union.append(member.slice)
else:
non_literals_in_union = True
if isinstance(member, ast.Subscript) and _is_builtins_type(member.value):
type_subscripts_in_union.append(member.slice)
for literal in literals_in_union:
if isinstance(literal, ast.Tuple):
combined_literal_members.extend(literal.elts)
else:
combined_literal_members.append(literal)
return UnionAnalysis(
members_by_dump=members_by_dump,
dupes_in_union=any(len(lst) > 1 for lst in members_by_dump.values()),
builtins_classes_in_union=builtins_classes_in_union,
multiple_literals_in_union=len(literals_in_union) >= 2,
non_literals_in_union=non_literals_in_union,
combined_literal_members=combined_literal_members,
multiple_type_subscripts_in_union=len(type_subscripts_in_union) >= 2,
combined_type_subscripts=type_subscripts_in_union,
)
class TypingLiteralAnalysis(NamedTuple):
members_by_dump: defaultdict[str, list[ast.expr]]
members_without_none: list[ast.expr]
none_members: list[ast.expr]
contains_only_none: bool
def _analyse_typing_Literal(node: ast.Subscript) -> TypingLiteralAnalysis:
"""Return a tuple providing analysis of a `typing.Literal` slice."""
members_by_dump: defaultdict[str, list[ast.expr]] = defaultdict(list)
members_without_none: list[ast.expr] = []
none_members: list[ast.expr] = []
members = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
for member in members:
members_by_dump[ast.dump(member)].append(member)
if _is_None(member):
none_members.append(member)
else:
members_without_none.append(member)
return TypingLiteralAnalysis(
members_by_dump=members_by_dump,
members_without_none=members_without_none,
none_members=none_members,
contains_only_none=bool(none_members and not members_without_none),
)
_COMMON_METACLASSES = {
"type": "builtins",
"ABCMeta": "abc",
"EnumMeta": "enum",
"EnumType": "enum",
}
@dataclass(frozen=True)
class EnclosingClassContext:
node: ast.ClassDef
cls_name: str
bases_map: defaultdict[str, set[str | None]]
def contains_in_bases(self, obj: str, *, from_: AbstractSet[str]) -> bool:
if obj not in self.bases_map:
return False
if None in self.bases_map[obj]:
return True
return bool(self.bases_map[obj] & from_)
@cached_property
def is_protocol_class(self) -> bool:
return self.contains_in_bases("Protocol", from_=_TYPING_MODULES)
@cached_property
def is_typeddict_class(self) -> bool:
return self.contains_in_bases(
"TypedDict", from_=(_TYPING_MODULES | {"mypy_extensions"})
)
@cached_property
def is_enum_class(self) -> bool:
return any(base_name.endswith(("Enum", "Flag")) for base_name in self.bases_map)
@cached_property
def is_metaclass(self) -> bool:
return any(
self.contains_in_bases(metacls, from_={module})
for metacls, module in _COMMON_METACLASSES.items()
)
@cached_property
def is_decorated_with_final(self) -> bool:
return any(_is_final(decorator) for decorator in self.node.decorator_list)
class ClassBase(NamedTuple):
module: str | None
obj: str
def _analyze_classdef(node: ast.ClassDef) -> EnclosingClassContext:
bases_map: defaultdict[str, set[str | None]] = defaultdict(set)
def _unravel(node: ast.expr) -> str | None:
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
value = _unravel(node.value)
if value is None:
return None
return f"{value}.{node.attr}"
return None
def _analyze_base_node(
base_node: ast.expr, top_level: bool = True
) -> ClassBase | None:
if isinstance(base_node, ast.Name):
return ClassBase(None, base_node.id)
if isinstance(base_node, ast.Attribute):
value = _unravel(base_node.value)
if value is None:
return None
return ClassBase(value, base_node.attr)
if isinstance(base_node, ast.Subscript) and top_level:
return _analyze_base_node(base_node.value, top_level=False)
return None
for base_node in node.bases:
base = _analyze_base_node(base_node)
if base is None:
continue
bases_map[base.obj].add(base.module)
return EnclosingClassContext(node=node, cls_name=node.name, bases_map=bases_map)
_ALLOWED_MATH_ATTRIBUTES_IN_DEFAULTS = frozenset(
{"math.inf", "math.nan", "math.e", "math.pi", "math.tau"}
)
_ALLOWED_ATTRIBUTES_IN_DEFAULTS = frozenset(
{
"sys.base_prefix",
"sys.byteorder",
"sys.exec_prefix",
"sys.executable",
"sys.hexversion",
"sys.maxsize",
"sys.platform",
"sys.prefix",
"sys.stdin",
"sys.stdout",
"sys.stderr",
"sys.version",
"sys.version_info",
"sys.winver",
"_typeshed.sentinel",
}
)
_ALLOWED_SIMPLE_ATTRIBUTES_IN_DEFAULTS = frozenset({"sentinel"})
def _is_valid_default_value_with_annotation(
node: ast.expr, *, allow_containers: bool = True
) -> bool:
"""Is `node` valid as a default value for a function or method parameter in a stub?
Note that this function is *also* used to determine
the validity of default values for ast.AnnAssign nodes.
(E.g. `foo: int = 5` is OK, but `foo: TypeVar = TypeVar("foo")` is not.)
"""
# lists, tuples, sets
if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
return (
allow_containers
and len(node.elts) <= 10
and all(
_is_valid_default_value_with_annotation(elt, allow_containers=False)
for elt in node.elts
)
)
# dicts
if isinstance(node, ast.Dict):
return (
allow_containers
and len(node.keys) <= 10
and all(
(
subnode is not None
and _is_valid_default_value_with_annotation(
subnode, allow_containers=False
)
)
for subnode in chain(node.keys, node.values)
)
)
# `...`, bools, None, str, bytes,
# positive ints, positive floats, positive complex numbers with no real part
if isinstance(node, ast.Constant):
return True
# Negative ints, negative floats, negative complex numbers with no real part,
# some constants from the math module
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
numeric_types = {int, float, complex}
if (
isinstance(node.operand, ast.Constant)
and type(node.operand.value) in numeric_types
):
return True
if isinstance(node.operand, ast.Attribute) and isinstance(
node.operand.value, ast.Name
):
fullname = f"{node.operand.value.id}.{node.operand.attr}"
return (
fullname in _ALLOWED_MATH_ATTRIBUTES_IN_DEFAULTS
and fullname != "math.nan"
)
return False
# Complex numbers with a real part and an imaginary part...
if (
isinstance(node, ast.BinOp)
and isinstance(node.op, (ast.Add, ast.Sub))
and isinstance(node.right, ast.Constant)
and type(node.right.value) is complex
):
left = node.left
# ...Where the real part is positive:
if isinstance(left, ast.Constant) and type(left.value) in {int, float}:
return True
# ...Where the real part is negative:
if (
isinstance(left, ast.UnaryOp)
and isinstance(left.op, ast.USub)
and isinstance(left.operand, ast.Constant)
and type(left.operand.value) in {int, float}
):
return True
return False
# Special cases
if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
fullname = f"{node.value.id}.{node.attr}"
return (fullname in _ALLOWED_ATTRIBUTES_IN_DEFAULTS) or (
fullname in _ALLOWED_MATH_ATTRIBUTES_IN_DEFAULTS
)
if isinstance(node, ast.Name):
return node.id in _ALLOWED_SIMPLE_ATTRIBUTES_IN_DEFAULTS
return False
def _is_valid_pep_604_union_member(node: ast.expr) -> bool:
return _is_None(node) or isinstance(node, (ast.Name, ast.Attribute, ast.Subscript))
def _is_valid_pep_604_union(node: ast.expr) -> TypeGuard[ast.BinOp]:
"""Does `node` represent a valid PEP-604 union (e.g. `int | str`)?"""
return (
isinstance(node, ast.BinOp)
and isinstance(node.op, ast.BitOr)
and (
_is_valid_pep_604_union_member(node.left)
or _is_valid_pep_604_union(node.left)
)
and _is_valid_pep_604_union_member(node.right)
)
def _is_valid_default_value_without_annotation(node: ast.expr) -> bool:
"""Is `node` a valid default for an assignment without an annotation?"""
return (
isinstance(node, (ast.Call, ast.Name, ast.Attribute, ast.Subscript))
or (isinstance(node, ast.Constant) and node.value in {None, ...})
or _is_valid_pep_604_union(node)
)
def _check_import_or_attribute(
node: ast.Attribute | ast.ImportFrom, module_name: str, object_name: str
) -> str | None:
"""If `node` represents a bad import, return the approriate error message.
Else, return None.
"""
fullname = f"{module_name}.{object_name}"
# Y057 errors
if fullname in {"typing.ByteString", "collections.abc.ByteString"}:
return Y057.format(module=module_name)
# Y024 errors
if fullname == "collections.namedtuple":
return Y024
if module_name in _TYPING_MODULES:
# Y022 errors
if object_name in _BAD_Y022_IMPORTS:
good_cls_name, slice_contents = _BAD_Y022_IMPORTS[object_name]
params = "" if slice_contents is None else f"[{slice_contents}]"
return Y022.format(
good_syntax=f'"{good_cls_name}{params}"',
bad_syntax=f'"{fullname}{params}"',
)
# Y037 errors
if object_name == "Optional":
return Y037.format(
old_syntax=fullname, example='"int | None" instead of "Optional[int]"'
)
if object_name == "Union":
return Y037.format(
old_syntax=fullname, example='"int | str" instead of "Union[int, str]"'
)
# Y039 errors
if object_name == "Text":
return Y039.format(module=module_name)
# Y023 errors
if module_name == "typing_extensions":
if object_name in _BAD_TYPINGEXTENSIONS_Y023_IMPORTS:
return Y023.format(
good_syntax=f'"typing.{object_name}"',
bad_syntax=f'"typing_extensions.{object_name}"',
)
if object_name == "ClassVar":
return Y023.format(
good_syntax='"typing.ClassVar[T]"',
bad_syntax='"typing_extensions.ClassVar[T]"',
)
return None
@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):
filename: str
errors: list[Error]
# Mapping of all private TypeVars/ParamSpecs/TypeVarTuples
# to the nodes where they're defined.
#
# The value type is a list, because any given TypeVar
# could have multiple definitions,
# e.g. in different sys.version_info branches
typevarlike_defs: defaultdict[TypeVarInfo, list[ast.Assign]]
# The same for private protocol definitions
protocol_defs: defaultdict[str, list[ast.ClassDef]]
# The same for class-based private TypedDicts
class_based_typeddicts: defaultdict[str, list[ast.ClassDef]]
# And for assignment-based TypedDicts
assignment_based_typeddicts: defaultdict[str, list[ast.Assign]]
# And for private TypeAliases
typealias_decls: defaultdict[str, list[_TypeAliasNodeType]]
# Mapping of each name in the file to the no. of occurrences
all_name_occurrences: Counter[str]
string_literals_allowed: NestingCounter
long_strings_allowed: NestingCounter
in_function: NestingCounter
visiting_arg: NestingCounter