forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstubtest.py
2087 lines (1817 loc) · 81.1 KB
/
stubtest.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
"""Tests for stubs.
Verify that various things in stubs are consistent with how things behave at runtime.
"""
from __future__ import annotations
import argparse
import collections.abc
import copy
import enum
import functools
import importlib
import importlib.machinery
import inspect
import os
import pkgutil
import re
import symtable
import sys
import traceback
import types
import typing
import typing_extensions
import warnings
from collections import defaultdict
from contextlib import redirect_stderr, redirect_stdout
from functools import singledispatch
from pathlib import Path
from typing import AbstractSet, Any, Generic, Iterator, TypeVar, Union
from typing_extensions import get_origin, is_typeddict
import mypy.build
import mypy.modulefinder
import mypy.nodes
import mypy.state
import mypy.types
import mypy.version
from mypy import nodes
from mypy.config_parser import parse_config_file
from mypy.evalexpr import UNKNOWN, evaluate_expression
from mypy.options import Options
from mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s
class Missing:
"""Marker object for things that are missing (from a stub or the runtime)."""
def __repr__(self) -> str:
return "MISSING"
MISSING: typing_extensions.Final = Missing()
T = TypeVar("T")
MaybeMissing: typing_extensions.TypeAlias = Union[T, Missing]
class Unrepresentable:
"""Marker object for unrepresentable parameter defaults."""
def __repr__(self) -> str:
return "<unrepresentable>"
UNREPRESENTABLE: typing_extensions.Final = Unrepresentable()
_formatter: typing_extensions.Final = FancyFormatter(sys.stdout, sys.stderr, False)
def _style(message: str, **kwargs: Any) -> str:
"""Wrapper around mypy.util for fancy formatting."""
kwargs.setdefault("color", "none")
return _formatter.style(message, **kwargs)
def _truncate(message: str, length: int) -> str:
if len(message) > length:
return message[: length - 3] + "..."
return message
class StubtestFailure(Exception):
pass
class Error:
def __init__(
self,
object_path: list[str],
message: str,
stub_object: MaybeMissing[nodes.Node],
runtime_object: MaybeMissing[Any],
*,
stub_desc: str | None = None,
runtime_desc: str | None = None,
) -> None:
"""Represents an error found by stubtest.
:param object_path: Location of the object with the error,
e.g. ``["module", "Class", "method"]``
:param message: Error message
:param stub_object: The mypy node representing the stub
:param runtime_object: Actual object obtained from the runtime
:param stub_desc: Specialised description for the stub object, should you wish
:param runtime_desc: Specialised description for the runtime object, should you wish
"""
self.object_path = object_path
self.object_desc = ".".join(object_path)
self.message = message
self.stub_object = stub_object
self.runtime_object = runtime_object
self.stub_desc = stub_desc or str(getattr(stub_object, "type", stub_object))
if runtime_desc is None:
runtime_sig = safe_inspect_signature(runtime_object)
if runtime_sig is None:
self.runtime_desc = _truncate(repr(runtime_object), 100)
else:
runtime_is_async = inspect.iscoroutinefunction(runtime_object)
description = describe_runtime_callable(runtime_sig, is_async=runtime_is_async)
self.runtime_desc = _truncate(description, 100)
else:
self.runtime_desc = runtime_desc
def is_missing_stub(self) -> bool:
"""Whether or not the error is for something missing from the stub."""
return isinstance(self.stub_object, Missing)
def is_positional_only_related(self) -> bool:
"""Whether or not the error is for something being (or not being) positional-only."""
# TODO: This is hacky, use error codes or something more resilient
return "leading double underscore" in self.message
def get_description(self, concise: bool = False) -> str:
"""Returns a description of the error.
:param concise: Whether to return a concise, one-line description
"""
if concise:
return _style(self.object_desc, bold=True) + " " + self.message
stub_line = None
stub_file = None
if not isinstance(self.stub_object, Missing):
stub_line = self.stub_object.line
stub_node = get_stub(self.object_path[0])
if stub_node is not None:
stub_file = stub_node.path or None
stub_loc_str = ""
if stub_file:
stub_loc_str += f" in file {Path(stub_file)}"
if stub_line:
stub_loc_str += f"{':' if stub_file else ' at line '}{stub_line}"
runtime_line = None
runtime_file = None
if not isinstance(self.runtime_object, Missing):
try:
runtime_line = inspect.getsourcelines(self.runtime_object)[1]
except (OSError, TypeError, SyntaxError):
pass
try:
runtime_file = inspect.getsourcefile(self.runtime_object)
except TypeError:
pass
runtime_loc_str = ""
if runtime_file:
runtime_loc_str += f" in file {Path(runtime_file)}"
if runtime_line:
runtime_loc_str += f"{':' if runtime_file else ' at line '}{runtime_line}"
output = [
_style("error: ", color="red", bold=True),
_style(self.object_desc, bold=True),
" ",
self.message,
"\n",
"Stub:",
_style(stub_loc_str, dim=True),
"\n",
_style(self.stub_desc + "\n", color="blue", dim=True),
"Runtime:",
_style(runtime_loc_str, dim=True),
"\n",
_style(self.runtime_desc + "\n", color="blue", dim=True),
]
return "".join(output)
# ====================
# Core logic
# ====================
def silent_import_module(module_name: str) -> types.ModuleType:
with open(os.devnull, "w") as devnull:
with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull):
warnings.simplefilter("ignore")
runtime = importlib.import_module(module_name)
# Also run the equivalent of `from module import *`
# This could have the additional effect of loading not-yet-loaded submodules
# mentioned in __all__
__import__(module_name, fromlist=["*"])
return runtime
def test_module(module_name: str) -> Iterator[Error]:
"""Tests a given module's stub against introspecting it at runtime.
Requires the stub to have been built already, accomplished by a call to ``build_stubs``.
:param module_name: The module to test
"""
stub = get_stub(module_name)
if stub is None:
if not is_probably_private(module_name.split(".")[-1]):
runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else "N/A"
yield Error(
[module_name], "failed to find stubs", MISSING, None, runtime_desc=runtime_desc
)
return
try:
runtime = silent_import_module(module_name)
except KeyboardInterrupt:
raise
except BaseException as e:
note = ""
if isinstance(e, ModuleNotFoundError):
note = " Maybe install the runtime package or alter PYTHONPATH?"
yield Error(
[module_name], f"failed to import.{note} {type(e).__name__}: {e}", stub, MISSING
)
return
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
yield from verify(stub, runtime, [module_name])
except Exception as e:
bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0]
bottom_module = bottom_frame.f_globals.get("__name__", "")
# Pass on any errors originating from stubtest or mypy
# These can occur expectedly, e.g. StubtestFailure
if bottom_module == "__main__" or bottom_module.split(".")[0] == "mypy":
raise
yield Error(
[module_name],
f"encountered unexpected error, {type(e).__name__}: {e}",
stub,
runtime,
stub_desc="N/A",
runtime_desc=(
"This is most likely the fault of something very dynamic in your library. "
"It's also possible this is a bug in stubtest.\nIf in doubt, please "
"open an issue at https://github.com/python/mypy\n\n"
+ traceback.format_exc().strip()
),
)
@singledispatch
def verify(
stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str]
) -> Iterator[Error]:
"""Entry point for comparing a stub to a runtime object.
We use single dispatch based on the type of ``stub``.
:param stub: The mypy node representing a part of the stub
:param runtime: The runtime object corresponding to ``stub``
"""
yield Error(object_path, "is an unknown mypy node", stub, runtime)
def _verify_exported_names(
object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str]
) -> Iterator[Error]:
# note that this includes the case the stub simply defines `__all__: list[str]`
assert "__all__" in stub.names
public_names_in_stub = {m for m, o in stub.names.items() if o.module_public}
names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set)
names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub)
if not (names_in_runtime_not_stub or names_in_stub_not_runtime):
return
yield Error(
object_path + ["__all__"],
(
"names exported from the stub do not correspond to the names exported at runtime. "
"This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub"
),
# Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very
# relevant here, and it makes for a prettier error message
# This means this error will be ignored when using `--ignore-missing-stub`, which is
# desirable in at least the `names_in_runtime_not_stub` case
stub_object=MISSING,
runtime_object=MISSING,
stub_desc=(f"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}"),
runtime_desc=(
f"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}"
),
)
@functools.lru_cache
def _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None:
"""Retrieve the symbol table for the module (or None on failure).
1) Use inspect to retrieve the source code of the module
2) Use symtable to parse the source (and use what symtable knows for its purposes)
"""
try:
source = inspect.getsource(runtime)
except (OSError, TypeError, SyntaxError):
return None
try:
return symtable.symtable(source, runtime.__name__, "exec")
except SyntaxError:
return None
@verify.register(nodes.MypyFile)
def verify_mypyfile(
stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]
) -> Iterator[Error]:
if isinstance(runtime, Missing):
yield Error(object_path, "is not present at runtime", stub, runtime)
return
if not isinstance(runtime, types.ModuleType):
yield Error(object_path, "is not a module", stub, runtime)
return
runtime_all_as_set: set[str] | None
if hasattr(runtime, "__all__"):
runtime_all_as_set = set(runtime.__all__)
if "__all__" in stub.names:
# Only verify the contents of the stub's __all__
# if the stub actually defines __all__
yield from _verify_exported_names(object_path, stub, runtime_all_as_set)
else:
runtime_all_as_set = None
# Check things in the stub
to_check = {
m
for m, o in stub.names.items()
if not o.module_hidden and (not is_probably_private(m) or hasattr(runtime, m))
}
def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
"""Heuristics to determine whether a name originates from another module."""
obj = getattr(r, attr)
if isinstance(obj, types.ModuleType):
return False
symbol_table = _module_symbol_table(r)
if symbol_table is not None:
try:
symbol = symbol_table.lookup(attr)
except KeyError:
pass
else:
if symbol.is_imported():
# symtable says we got this from another module
return False
# But we can't just return True here, because symtable doesn't know about symbols
# that come from `from module import *`
if symbol.is_assigned():
# symtable knows we assigned this symbol in the module
return True
# The __module__ attribute is unreliable for anything except functions and classes,
# but it's our best guess at this point
try:
obj_mod = obj.__module__
except Exception:
pass
else:
if isinstance(obj_mod, str):
return bool(obj_mod == r.__name__)
return True
runtime_public_contents = (
runtime_all_as_set
if runtime_all_as_set is not None
else {
m
for m in dir(runtime)
if not is_probably_private(m)
# Filter out objects that originate from other modules (best effort). Note that in the
# absence of __all__, we don't have a way to detect explicit / intentional re-exports
# at runtime
and _belongs_to_runtime(runtime, m)
}
)
# Check all things declared in module's __all__, falling back to our best guess
to_check.update(runtime_public_contents)
to_check.difference_update(IGNORED_MODULE_DUNDERS)
for entry in sorted(to_check):
stub_entry = stub.names[entry].node if entry in stub.names else MISSING
if isinstance(stub_entry, nodes.MypyFile):
# Don't recursively check exported modules, since that leads to infinite recursion
continue
assert stub_entry is not None
try:
runtime_entry = getattr(runtime, entry, MISSING)
except Exception:
# Catch all exceptions in case the runtime raises an unexpected exception
# from __getattr__ or similar.
continue
yield from verify(stub_entry, runtime_entry, object_path + [entry])
def _verify_final(
stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str]
) -> Iterator[Error]:
try:
class SubClass(runtime): # type: ignore[misc]
pass
except TypeError:
# Enum classes are implicitly @final
if not stub.is_final and not issubclass(runtime, enum.Enum):
yield Error(
object_path,
"cannot be subclassed at runtime, but isn't marked with @final in the stub",
stub,
runtime,
stub_desc=repr(stub),
)
except Exception:
# The class probably wants its subclasses to do something special.
# Examples: ctypes.Array, ctypes._SimpleCData
pass
# Runtime class might be annotated with `@final`:
try:
runtime_final = getattr(runtime, "__final__", False)
except Exception:
runtime_final = False
if runtime_final and not stub.is_final:
yield Error(
object_path,
"has `__final__` attribute, but isn't marked with @final in the stub",
stub,
runtime,
stub_desc=repr(stub),
)
def _verify_metaclass(
stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool
) -> Iterator[Error]:
# We exclude protocols, because of how complex their implementation is in different versions of
# python. Enums are also hard, as are runtime TypedDicts; ignoring.
# TODO: check that metaclasses are identical?
if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict:
runtime_metaclass = type(runtime)
if runtime_metaclass is not type and stub.metaclass_type is None:
# This means that runtime has a custom metaclass, but a stub does not.
yield Error(
object_path,
"is inconsistent, metaclass differs",
stub,
runtime,
stub_desc="N/A",
runtime_desc=f"{runtime_metaclass}",
)
elif (
runtime_metaclass is type
and stub.metaclass_type is not None
# We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack.
# We also ignore `builtins.type` metaclass as an implementation detail in mypy.
and not mypy.types.is_named_instance(
stub.metaclass_type, ("abc.ABCMeta", "builtins.type")
)
):
# This means that our stub has a metaclass that is not present at runtime.
yield Error(
object_path,
"metaclass mismatch",
stub,
runtime,
stub_desc=f"{stub.metaclass_type.type.fullname}",
runtime_desc="N/A",
)
@verify.register(nodes.TypeInfo)
def verify_typeinfo(
stub: nodes.TypeInfo, runtime: MaybeMissing[type[Any]], object_path: list[str]
) -> Iterator[Error]:
if stub.is_type_check_only:
# This type only exists in stubs, we only check that the runtime part
# is missing. Other checks are not required.
if not isinstance(runtime, Missing):
yield Error(
object_path,
'is marked as "@type_check_only", but also exists at runtime',
stub,
runtime,
stub_desc=repr(stub),
)
return
if isinstance(runtime, Missing):
yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=repr(stub))
return
if not isinstance(runtime, type):
yield Error(object_path, "is not a type", stub, runtime, stub_desc=repr(stub))
return
yield from _verify_final(stub, runtime, object_path)
is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime)
yield from _verify_metaclass(
stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict
)
# Check everything already defined on the stub class itself (i.e. not inherited)
#
# Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things
# (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime,
# and exist purely for internal mypy reasons
to_check = {name for name in stub.names if name.isidentifier()}
# Check all public things on the runtime class
to_check.update(
m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS
)
# Special-case the __init__ method for Protocols and the __new__ method for TypedDicts
#
# TODO: On Python <3.11, __init__ methods on Protocol classes
# are silently discarded and replaced.
# However, this is not the case on Python 3.11+.
# Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+.
if stub.is_protocol:
to_check.discard("__init__")
if is_runtime_typeddict:
to_check.discard("__new__")
for entry in sorted(to_check):
mangled_entry = entry
if entry.startswith("__") and not entry.endswith("__"):
mangled_entry = f"_{stub.name.lstrip('_')}{entry}"
stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING)
assert stub_to_verify is not None
try:
try:
runtime_attr = getattr(runtime, mangled_entry)
except AttributeError:
runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)
except Exception:
# Catch all exceptions in case the runtime raises an unexpected exception
# from __getattr__ or similar.
continue
# Do not error for an object missing from the stub
# If the runtime object is a types.WrapperDescriptorType object
# and has a non-special dunder name.
# The vast majority of these are false positives.
if not (
isinstance(stub_to_verify, Missing)
and isinstance(runtime_attr, types.WrapperDescriptorType)
and is_dunder(mangled_entry, exclude_special=True)
):
yield from verify(stub_to_verify, runtime_attr, object_path + [entry])
def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]:
static_runtime = importlib.import_module(object_path[0])
for entry in object_path[1:]:
try:
static_runtime = inspect.getattr_static(static_runtime, entry)
except AttributeError:
# This can happen with mangled names, ignore for now.
# TODO: pass more information about ancestors of nodes/objects to verify, so we don't
# have to do this hacky lookup. Would be useful in several places.
return MISSING
return static_runtime
def _verify_static_class_methods(
stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str]
) -> Iterator[str]:
if stub.name in ("__new__", "__init_subclass__", "__class_getitem__"):
# Special cased by Python, so don't bother checking
return
if inspect.isbuiltin(runtime):
# The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do
# something a little hacky that seems to work well
probably_class_method = isinstance(getattr(runtime, "__self__", None), type)
if probably_class_method and not stub.is_class:
yield "runtime is a classmethod but stub is not"
if not probably_class_method and stub.is_class:
yield "stub is a classmethod but runtime is not"
return
if static_runtime is MISSING:
return
if isinstance(static_runtime, classmethod) and not stub.is_class:
yield "runtime is a classmethod but stub is not"
if not isinstance(static_runtime, classmethod) and stub.is_class:
yield "stub is a classmethod but runtime is not"
if isinstance(static_runtime, staticmethod) and not stub.is_static:
yield "runtime is a staticmethod but stub is not"
if not isinstance(static_runtime, staticmethod) and stub.is_static:
yield "stub is a staticmethod but runtime is not"
def _verify_arg_name(
stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str
) -> Iterator[str]:
"""Checks whether argument names match."""
# Ignore exact names for most dunder methods
if is_dunder(function_name, exclude_special=True):
return
def strip_prefix(s: str, prefix: str) -> str:
return s[len(prefix) :] if s.startswith(prefix) else s
if strip_prefix(stub_arg.variable.name, "__") == runtime_arg.name:
return
nonspecific_names = {"object", "args"}
if runtime_arg.name in nonspecific_names:
return
def names_approx_match(a: str, b: str) -> bool:
a = a.strip("_")
b = b.strip("_")
return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1
# Be more permissive about names matching for positional-only arguments
if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match(
stub_arg.variable.name, runtime_arg.name
):
return
# This comes up with namedtuples, so ignore
if stub_arg.variable.name == "_self":
return
yield (
f'stub argument "{stub_arg.variable.name}" '
f'differs from runtime argument "{runtime_arg.name}"'
)
def _verify_arg_default_value(
stub_arg: nodes.Argument, runtime_arg: inspect.Parameter
) -> Iterator[str]:
"""Checks whether argument default values are compatible."""
if runtime_arg.default != inspect.Parameter.empty:
if stub_arg.kind.is_required():
yield (
f'runtime argument "{runtime_arg.name}" '
"has a default value but stub argument does not"
)
else:
runtime_type = get_mypy_type_of_runtime_value(runtime_arg.default)
# Fallback to the type annotation type if var type is missing. The type annotation
# is an UnboundType, but I don't know enough to know what the pros and cons here are.
# UnboundTypes have ugly question marks following them, so default to var type.
# Note we do this same fallback when constructing signatures in from_overloadedfuncdef
stub_type = stub_arg.variable.type or stub_arg.type_annotation
if isinstance(stub_type, mypy.types.TypeVarType):
stub_type = stub_type.upper_bound
if (
runtime_type is not None
and stub_type is not None
# Avoid false positives for marker objects
and type(runtime_arg.default) is not object
# And ellipsis
and runtime_arg.default is not ...
and not is_subtype_helper(runtime_type, stub_type)
):
yield (
f'runtime argument "{runtime_arg.name}" '
f"has a default value of type {runtime_type}, "
f"which is incompatible with stub argument type {stub_type}"
)
if stub_arg.initializer is not None:
stub_default = evaluate_expression(stub_arg.initializer)
if (
stub_default is not UNKNOWN
and stub_default is not ...
and runtime_arg.default is not UNREPRESENTABLE
and (
stub_default != runtime_arg.default
# We want the types to match exactly, e.g. in case the stub has
# True and the runtime has 1 (or vice versa).
or type(stub_default) is not type(runtime_arg.default) # noqa: E721
)
):
yield (
f'runtime argument "{runtime_arg.name}" '
f"has a default value of {runtime_arg.default!r}, "
f"which is different from stub argument default {stub_default!r}"
)
else:
if stub_arg.kind.is_optional():
yield (
f'stub argument "{stub_arg.variable.name}" has a default value '
f"but runtime argument does not"
)
def maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]:
if args and name in ("__init_subclass__", "__class_getitem__"):
# These are implicitly classmethods. If the stub chooses not to have @classmethod, we
# should remove the cls argument
if args[0].variable.name == "cls":
return args[1:]
return args
class Signature(Generic[T]):
def __init__(self) -> None:
self.pos: list[T] = []
self.kwonly: dict[str, T] = {}
self.varpos: T | None = None
self.varkw: T | None = None
def __str__(self) -> str:
def get_name(arg: Any) -> str:
if isinstance(arg, inspect.Parameter):
return arg.name
if isinstance(arg, nodes.Argument):
return arg.variable.name
raise AssertionError
def get_type(arg: Any) -> str | None:
if isinstance(arg, inspect.Parameter):
return None
if isinstance(arg, nodes.Argument):
return str(arg.variable.type or arg.type_annotation)
raise AssertionError
def has_default(arg: Any) -> bool:
if isinstance(arg, inspect.Parameter):
return bool(arg.default != inspect.Parameter.empty)
if isinstance(arg, nodes.Argument):
return arg.kind.is_optional()
raise AssertionError
def get_desc(arg: Any) -> str:
arg_type = get_type(arg)
return (
get_name(arg)
+ (f": {arg_type}" if arg_type else "")
+ (" = ..." if has_default(arg) else "")
)
kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a)))
ret = "def ("
ret += ", ".join(
[get_desc(arg) for arg in self.pos]
+ (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else []))
+ [get_desc(arg) for arg in kw_only]
+ (["**" + get_name(self.varkw)] if self.varkw else [])
)
ret += ")"
return ret
@staticmethod
def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]:
stub_sig: Signature[nodes.Argument] = Signature()
stub_args = maybe_strip_cls(stub.name, stub.arguments)
for stub_arg in stub_args:
if stub_arg.kind.is_positional():
stub_sig.pos.append(stub_arg)
elif stub_arg.kind.is_named():
stub_sig.kwonly[stub_arg.variable.name] = stub_arg
elif stub_arg.kind == nodes.ARG_STAR:
stub_sig.varpos = stub_arg
elif stub_arg.kind == nodes.ARG_STAR2:
stub_sig.varkw = stub_arg
else:
raise AssertionError
return stub_sig
@staticmethod
def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]:
runtime_sig: Signature[inspect.Parameter] = Signature()
for runtime_arg in signature.parameters.values():
if runtime_arg.kind in (
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
):
runtime_sig.pos.append(runtime_arg)
elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY:
runtime_sig.kwonly[runtime_arg.name] = runtime_arg
elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL:
runtime_sig.varpos = runtime_arg
elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD:
runtime_sig.varkw = runtime_arg
else:
raise AssertionError
return runtime_sig
@staticmethod
def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]:
"""Returns a Signature from an OverloadedFuncDef.
If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its
items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we
try and combine the overload's items into a single signature that is compatible with any
lies it might try to tell.
"""
# For most dunder methods, just assume all args are positional-only
assume_positional_only = is_dunder(stub.name, exclude_special=True)
all_args: dict[str, list[tuple[nodes.Argument, int]]] = {}
for func in map(_resolve_funcitem_from_decorator, stub.items):
assert func is not None
args = maybe_strip_cls(stub.name, func.arguments)
for index, arg in enumerate(args):
# For positional-only args, we allow overloads to have different names for the same
# argument. To accomplish this, we just make up a fake index-based name.
name = (
f"__{index}"
if arg.variable.name.startswith("__")
or arg.pos_only
or assume_positional_only
or arg.variable.name.strip("_") == "self"
else arg.variable.name
)
all_args.setdefault(name, []).append((arg, index))
def get_position(arg_name: str) -> int:
# We just need this to return the positional args in the correct order.
return max(index for _, index in all_args[arg_name])
def get_type(arg_name: str) -> mypy.types.ProperType:
with mypy.state.state.strict_optional_set(True):
all_types = [
arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name]
]
return mypy.typeops.make_simplified_union([t for t in all_types if t])
def get_kind(arg_name: str) -> nodes.ArgKind:
kinds = {arg.kind for arg, _ in all_args[arg_name]}
if nodes.ARG_STAR in kinds:
return nodes.ARG_STAR
if nodes.ARG_STAR2 in kinds:
return nodes.ARG_STAR2
# The logic here is based on two tenets:
# 1) If an arg is ever optional (or unspecified), it is optional
# 2) If an arg is ever positional, it is positional
is_opt = (
len(all_args[arg_name]) < len(stub.items)
or nodes.ARG_OPT in kinds
or nodes.ARG_NAMED_OPT in kinds
)
is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds
if is_opt:
return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT
return nodes.ARG_POS if is_pos else nodes.ARG_NAMED
sig: Signature[nodes.Argument] = Signature()
for arg_name in sorted(all_args, key=get_position):
# example_arg_name gives us a real name (in case we had a fake index-based name)
example_arg_name = all_args[arg_name][0][0].variable.name
arg = nodes.Argument(
nodes.Var(example_arg_name, get_type(arg_name)),
type_annotation=None,
initializer=None,
kind=get_kind(arg_name),
pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]),
)
if arg.kind.is_positional():
sig.pos.append(arg)
elif arg.kind.is_named():
sig.kwonly[arg.variable.name] = arg
elif arg.kind == nodes.ARG_STAR:
sig.varpos = arg
elif arg.kind == nodes.ARG_STAR2:
sig.varkw = arg
else:
raise AssertionError
return sig
def _verify_signature(
stub: Signature[nodes.Argument], runtime: Signature[inspect.Parameter], function_name: str
) -> Iterator[str]:
# Check positional arguments match up
for stub_arg, runtime_arg in zip(stub.pos, runtime.pos):
yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
yield from _verify_arg_default_value(stub_arg, runtime_arg)
if (
runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY
and not stub_arg.pos_only
and not stub_arg.variable.name.startswith("__")
and stub_arg.variable.name.strip("_") != "self"
and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods
):
yield (
f'stub argument "{stub_arg.variable.name}" should be positional-only '
f'(rename with a leading double underscore, i.e. "__{runtime_arg.name}")'
)
if (
runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY
and (stub_arg.pos_only or stub_arg.variable.name.startswith("__"))
and stub_arg.variable.name.strip("_") != "self"
and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods
):
yield (
f'stub argument "{stub_arg.variable.name}" should be positional or keyword '
"(remove leading double underscore)"
)
# Check unmatched positional args
if len(stub.pos) > len(runtime.pos):
# There are cases where the stub exhaustively lists out the extra parameters the function
# would take through *args. Hence, a) if runtime accepts *args, we don't check whether the
# runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes
# *args, since runtime logic may prevent arbitrary arguments from actually being accepted.
if runtime.varpos is None:
for stub_arg in stub.pos[len(runtime.pos) :]:
# If the variable is in runtime.kwonly, it's just mislabelled as not a
# keyword-only argument
if stub_arg.variable.name not in runtime.kwonly:
msg = f'runtime does not have argument "{stub_arg.variable.name}"'
if runtime.varkw is not None:
msg += ". Maybe you forgot to make it keyword-only in the stub?"
yield msg
else:
yield f'stub argument "{stub_arg.variable.name}" is not keyword-only'
if stub.varpos is not None:
yield f'runtime does not have *args argument "{stub.varpos.variable.name}"'
elif len(stub.pos) < len(runtime.pos):
for runtime_arg in runtime.pos[len(stub.pos) :]:
if runtime_arg.name not in stub.kwonly:
if not _is_private_parameter(runtime_arg):
yield f'stub does not have argument "{runtime_arg.name}"'
else:
yield f'runtime argument "{runtime_arg.name}" is not keyword-only'
# Checks involving *args
if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None:
if stub.varpos is None and runtime.varpos is not None:
yield f'stub does not have *args argument "{runtime.varpos.name}"'
if stub.varpos is not None and runtime.varpos is None:
yield f'runtime does not have *args argument "{stub.varpos.variable.name}"'
# Check keyword-only args
for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)):
stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg]
yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
yield from _verify_arg_default_value(stub_arg, runtime_arg)
# Check unmatched keyword-only args
if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)):
# There are cases where the stub exhaustively lists out the extra parameters the function
# would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't
# exhaustively listed out params), we don't check whether the runtime has all of the stub's
# parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic
# may prevent arbitrary keyword arguments from actually being accepted.
for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)):
if arg in {runtime_arg.name for runtime_arg in runtime.pos}:
# Don't report this if we've reported it before
if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}:
yield f'runtime argument "{arg}" is not keyword-only'
else:
yield f'runtime does not have argument "{arg}"'
for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)):
if arg in {stub_arg.variable.name for stub_arg in stub.pos}:
# Don't report this if we've reported it before
if not (
runtime.varpos is None
and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]}
):
yield f'stub argument "{arg}" is not keyword-only'
else:
if not _is_private_parameter(runtime.kwonly[arg]):
yield f'stub does not have argument "{arg}"'
# Checks involving **kwargs
if stub.varkw is None and runtime.varkw is not None:
# As mentioned above, don't enforce that the stub takes **kwargs.
# Also check against positional parameters, to avoid a nitpicky message when an argument
# isn't marked as keyword-only
stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos}
# Ideally we'd do a strict subset check, but in practice the errors from that aren't useful
if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names):
yield f'stub does not have **kwargs argument "{runtime.varkw.name}"'
if stub.varkw is not None and runtime.varkw is None: