Debian Codegraph @

mypy/stubtest.py

raw
1 """Tests for stubs.
2
3 Verify that various things in stubs are consistent with how things behave at runtime.
4
5 """
6
7 from __future__ import annotations
8
9 import argparse
10 import collections.abc
11 import copy
12 import enum
13 import functools
14 import importlib
15 import inspect
16 import keyword
17 import os
18 import pkgutil
19 import re
20 import struct
21 import symtable
22 import sys
23 import traceback
24 import types
25 import typing
26 import typing_extensions
27 import warnings
28 from collections import defaultdict
29 from collections.abc import Iterator
30 from contextlib import redirect_stderr, redirect_stdout
31 from functools import singledispatch
32 from pathlib import Path
33 from typing import Any, Final, Generic, TypeVar, Union, get_origin
34 from typing_extensions import is_typeddict
35
36 import mypy.build
37 import mypy.checkexpr
38 import mypy.erasetype
39 import mypy.modulefinder
40 import mypy.nodes
41 import mypy.state
42 import mypy.subtypes
43 import mypy.types
44 import mypy.version
45 from mypy import nodes
46 from mypy.config_parser import parse_config_file
47 from mypy.evalexpr import UNKNOWN, evaluate_expression
48 from mypy.maptype import map_instance_to_supertype
49 from mypy.options import Options
50 from mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s
51
52
53 class Missing:
54 """Marker object for things that are missing (from a stub or the runtime)."""
55
56 def __repr__(self) -> str:
57 return "MISSING"
58
59
60 MISSING: Final = Missing()
61
62 T = TypeVar("T")
63 MaybeMissing: typing_extensions.TypeAlias = T | Missing
64
65
66 class Unrepresentable:
67 """Marker object for unrepresentable parameter defaults."""
68
69 def __repr__(self) -> str:
70 return "<unrepresentable>"
71
72
73 UNREPRESENTABLE: Final = Unrepresentable()
74
75
76 _formatter: Final = FancyFormatter(sys.stdout, sys.stderr, False)
77
78
79 def _style(message: str, **kwargs: Any) -> str:
80 """Wrapper around mypy.util for fancy formatting."""
81 kwargs.setdefault("color", "none")
82 return _formatter.style(message, **kwargs)
83
84
85 def _truncate(message: str, length: int) -> str:
86 if len(message) > length:
87 return message[: length - 3] + "..."
88 return message
89
90
91 class StubtestFailure(Exception):
92 pass
93
94
95 class Error:
96 def __init__(
97 self,
98 object_path: list[str],
99 message: str,
100 stub_object: MaybeMissing[nodes.Node],
101 runtime_object: MaybeMissing[Any],
102 *,
103 stub_desc: str | None = None,
104 runtime_desc: str | None = None,
105 ) -> None:
106 """Represents an error found by stubtest.
107
108 :param object_path: Location of the object with the error,
109 e.g. ``["module", "Class", "method"]``
110 :param message: Error message
111 :param stub_object: The mypy node representing the stub
112 :param runtime_object: Actual object obtained from the runtime
113 :param stub_desc: Specialised description for the stub object, should you wish
114 :param runtime_desc: Specialised description for the runtime object, should you wish
115
116 """
117 self.object_path = object_path
118 self.object_desc = ".".join(object_path)
119 self.message = message
120 self.stub_object = stub_object
121 self.runtime_object = runtime_object
122 self.stub_desc = stub_desc or str(getattr(stub_object, "type", stub_object))
123
124 if runtime_desc is None:
125 runtime_sig = safe_inspect_signature(runtime_object)
126 if runtime_sig is None:
127 self.runtime_desc = _truncate(repr(runtime_object), 100)
128 else:
129 runtime_is_async = inspect.iscoroutinefunction(runtime_object)
130 description = describe_runtime_callable(runtime_sig, is_async=runtime_is_async)
131 self.runtime_desc = _truncate(description, 100)
132 else:
133 self.runtime_desc = runtime_desc
134
135 def is_missing_stub(self) -> bool:
136 """Whether or not the error is for something missing from the stub."""
137 return isinstance(self.stub_object, Missing)
138
139 def is_positional_only_related(self) -> bool:
140 """Whether or not the error is for something being (or not being) positional-only."""
141 # TODO: This is hacky, use error codes or something more resilient
142 return "should be positional" in self.message
143
144 def is_disjoint_base_related(self) -> bool:
145 """Whether or not the error is related to @disjoint_base."""
146 # TODO: This is hacky, use error codes or something more resilient
147 return "@disjoint_base" in self.message
148
149 def is_private_type_check_only_related(self) -> bool:
150 """Whether or not the error is related to @type_check_only on private types."""
151 # TODO: This is hacky, use error codes or something more resilient
152 return self.message.endswith('Maybe mark it as "@type_check_only"?')
153
154 def get_description(self, concise: bool = False) -> str:
155 """Returns a description of the error.
156
157 :param concise: Whether to return a concise, one-line description
158
159 """
160 if concise:
161 return _style(self.object_desc, bold=True) + " " + self.message
162
163 stub_line = None
164 stub_file = None
165 if not isinstance(self.stub_object, Missing):
166 stub_line = self.stub_object.line
167 stub_node = get_stub(self.object_path[0])
168 if stub_node is not None:
169 stub_file = stub_node.path or None
170
171 stub_loc_str = ""
172 if stub_file:
173 stub_loc_str += f" in file {Path(stub_file)}"
174 if stub_line:
175 stub_loc_str += f"{':' if stub_file else ' at line '}{stub_line}"
176
177 runtime_line = None
178 runtime_file = None
179 if not isinstance(self.runtime_object, Missing):
180 try:
181 runtime_line = inspect.getsourcelines(self.runtime_object)[1]
182 except (OSError, TypeError, SyntaxError):
183 pass
184 try:
185 runtime_file = inspect.getsourcefile(self.runtime_object)
186 except TypeError:
187 pass
188
189 runtime_loc_str = ""
190 if runtime_file:
191 runtime_loc_str += f" in file {Path(runtime_file)}"
192 if runtime_line:
193 runtime_loc_str += f"{':' if runtime_file else ' at line '}{runtime_line}"
194
195 output = [
196 _style("error: ", color="red", bold=True),
197 _style(self.object_desc, bold=True),
198 " ",
199 self.message,
200 "\n",
201 "Stub:",
202 _style(stub_loc_str, dim=True),
203 "\n",
204 _style(self.stub_desc + "\n", color="blue", dim=True),
205 "Runtime:",
206 _style(runtime_loc_str, dim=True),
207 "\n",
208 _style(self.runtime_desc + "\n", color="blue", dim=True),
209 ]
210 return "".join(output)
211
212
213 # ====================
214 # Core logic
215 # ====================
216
217
218 def silent_import_module(module_name: str) -> types.ModuleType:
219 with open(os.devnull, "w") as devnull:
220 with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull):
221 warnings.simplefilter("ignore")
222 runtime = importlib.import_module(module_name)
223 # Also run the equivalent of `from module import *`
224 # This could have the additional effect of loading not-yet-loaded submodules
225 # mentioned in __all__
226 __import__(module_name, fromlist=["*"])
227 return runtime
228
229
230 def test_module(module_name: str) -> Iterator[Error]:
231 """Tests a given module's stub against introspecting it at runtime.
232
233 Requires the stub to have been built already, accomplished by a call to ``build_stubs``.
234
235 :param module_name: The module to test
236
237 """
238 stub = get_stub(module_name)
239 if stub is None:
240 if not is_probably_private(module_name.split(".")[-1]):
241 runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else "N/A"
242 yield Error(
243 [module_name], "failed to find stubs", MISSING, None, runtime_desc=runtime_desc
244 )
245 return
246
247 try:
248 runtime = silent_import_module(module_name)
249 except KeyboardInterrupt:
250 raise
251 except BaseException as e:
252 note = ""
253 if isinstance(e, ModuleNotFoundError):
254 note = " Maybe install the runtime package or alter PYTHONPATH?"
255 yield Error(
256 [module_name], f"failed to import.{note} {type(e).__name__}: {e}", stub, MISSING
257 )
258 return
259
260 with warnings.catch_warnings():
261 warnings.simplefilter("ignore")
262 try:
263 yield from verify(stub, runtime, [module_name])
264 except Exception as e:
265 bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0]
266 bottom_module = bottom_frame.f_globals.get("__name__", "")
267 # Pass on any errors originating from stubtest or mypy
268 # These can occur expectedly, e.g. StubtestFailure
269 if bottom_module == "__main__" or bottom_module.split(".")[0] == "mypy":
270 raise
271 yield Error(
272 [module_name],
273 f"encountered unexpected error, {type(e).__name__}: {e}",
274 stub,
275 runtime,
276 stub_desc="N/A",
277 runtime_desc=(
278 "This is most likely the fault of something very dynamic in your library. "
279 "It's also possible this is a bug in stubtest.\nIf in doubt, please "
280 "open an issue at https://github.com/python/mypy\n\n"
281 + traceback.format_exc().strip()
282 ),
283 )
284
285
286 @singledispatch
287 def verify(
288 stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str]
289 ) -> Iterator[Error]:
290 """Entry point for comparing a stub to a runtime object.
291
292 We use single dispatch based on the type of ``stub``.
293
294 :param stub: The mypy node representing a part of the stub
295 :param runtime: The runtime object corresponding to ``stub``
296
297 """
298 yield Error(object_path, "is an unknown mypy node", stub, runtime)
299
300
301 def _verify_exported_names(
302 object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str]
303 ) -> Iterator[Error]:
304 # note that this includes the case the stub simply defines `__all__: list[str]`
305 assert "__all__" in stub.names
306 public_names_in_stub = {m for m, o in stub.names.items() if o.module_public}
307 names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set)
308 names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub)
309 if not (names_in_runtime_not_stub or names_in_stub_not_runtime):
310 return
311 yield Error(
312 object_path + ["__all__"],
313 (
314 "names exported from the stub do not correspond to the names exported at runtime. "
315 "This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub"
316 ),
317 # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very
318 # relevant here, and it makes for a prettier error message
319 # This means this error will be ignored when using `--ignore-missing-stub`, which is
320 # desirable in at least the `names_in_runtime_not_stub` case
321 stub_object=MISSING,
322 runtime_object=MISSING,
323 stub_desc=(f"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}"),
324 runtime_desc=(
325 f"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}"
326 ),
327 )
328
329
330 @functools.lru_cache
331 def _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None:
332 """Retrieve the symbol table for the module (or None on failure).
333
334 1) Use inspect to retrieve the source code of the module
335 2) Use symtable to parse the source (and use what symtable knows for its purposes)
336 """
337 try:
338 source = inspect.getsource(runtime)
339 except (OSError, TypeError, SyntaxError):
340 return None
341
342 try:
343 return symtable.symtable(source, runtime.__name__, "exec")
344 except SyntaxError:
345 return None
346
347
348 @verify.register(nodes.MypyFile)
349 def verify_mypyfile(
350 stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]
351 ) -> Iterator[Error]:
352 if isinstance(runtime, Missing):
353 yield Error(object_path, "is not present at runtime", stub, runtime)
354 return
355 if not isinstance(runtime, types.ModuleType):
356 # Can possibly happen:
357 yield Error(object_path, "is not a module", stub, runtime) # type: ignore[unreachable]
358 return
359
360 runtime_all_as_set: set[str] | None
361
362 if hasattr(runtime, "__all__"):
363 runtime_all_as_set = set(runtime.__all__)
364 if "__all__" in stub.names:
365 # Only verify the contents of the stub's __all__
366 # if the stub actually defines __all__
367 yield from _verify_exported_names(object_path, stub, runtime_all_as_set)
368 else:
369 yield Error(object_path + ["__all__"], "is not present in stub", MISSING, runtime)
370 else:
371 runtime_all_as_set = None
372
373 # Check things in the stub
374 to_check = {m for m, o in stub.names.items() if not o.module_hidden}
375
376 def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
377 """Heuristics to determine whether a name originates from another module."""
378 obj = getattr(r, attr)
379 if isinstance(obj, types.ModuleType):
380 return False
381
382 symbol_table = _module_symbol_table(r)
383 if symbol_table is not None:
384 try:
385 symbol = symbol_table.lookup(attr)
386 except KeyError:
387 pass
388 else:
389 if symbol.is_imported():
390 # symtable says we got this from another module
391 return False
392 # But we can't just return True here, because symtable doesn't know about symbols
393 # that come from `from module import *`
394 if symbol.is_assigned():
395 # symtable knows we assigned this symbol in the module
396 return True
397
398 # The __module__ attribute is unreliable for anything except functions and classes,
399 # but it's our best guess at this point
400 try:
401 obj_mod = obj.__module__
402 except Exception:
403 pass
404 else:
405 if isinstance(obj_mod, str):
406 return bool(obj_mod == r.__name__)
407 return True
408
409 runtime_public_contents = (
410 runtime_all_as_set
411 if runtime_all_as_set is not None
412 else {
413 m
414 for m in dir(runtime)
415 if not is_probably_private(m)
416 # Filter out objects that originate from other modules (best effort). Note that in the
417 # absence of __all__, we don't have a way to detect explicit / intentional re-exports
418 # at runtime
419 and _belongs_to_runtime(runtime, m)
420 }
421 )
422 # Check all things declared in module's __all__, falling back to our best guess
423 to_check.update(runtime_public_contents)
424 to_check.difference_update(IGNORED_MODULE_DUNDERS)
425
426 for entry in sorted(to_check):
427 stub_entry = stub.names[entry].node if entry in stub.names else MISSING
428 if entry in stub.names:
429 if xref := stub.names[entry].cross_ref:
430 orig_module = xref.rsplit(".", 1)[0]
431 elif isinstance(stub_entry, nodes.SymbolNode) and (name := stub_entry.fullname):
432 orig_module = name.rsplit(".", 1)[0]
433 else:
434 orig_module = None
435
436 if orig_module and orig_module != stub.fullname and orig_module in _all_stubs:
437 # Skip re-exported names whose defining module will be checked separately.
438 continue
439
440 if isinstance(stub_entry, nodes.MypyFile):
441 # Don't recursively check exported modules, since that leads to infinite recursion
442 continue
443 assert stub_entry is not None
444 if (
445 is_probably_private(entry)
446 and not hasattr(runtime, entry)
447 and not isinstance(stub_entry, Missing)
448 and not _is_decoratable(stub_entry)
449 ):
450 # Skip private names that don't exist at runtime and which cannot
451 # be marked with @type_check_only.
452 continue
453 try:
454 runtime_entry = getattr(runtime, entry, MISSING)
455 except Exception:
456 # Catch all exceptions in case the runtime raises an unexpected exception
457 # from __getattr__ or similar.
458 continue
459 yield from verify(stub_entry, runtime_entry, object_path + [entry])
460
461
462 def _is_decoratable(stub: nodes.SymbolNode) -> bool:
463 if not isinstance(stub, nodes.TypeInfo):
464 return False
465 if stub.is_newtype:
466 return False
467 if stub.typeddict_type is not None:
468 return all(
469 name.isidentifier() and not keyword.iskeyword(name)
470 for name in stub.typeddict_type.items.keys()
471 )
472 return True
473
474
475 def _verify_final(
476 stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str]
477 ) -> Iterator[Error]:
478 try:
479
480 class SubClass(runtime): # type: ignore[misc]
481 pass
482
483 except TypeError:
484 # Enum classes are implicitly @final
485 if not stub.is_final and not issubclass(runtime, enum.Enum):
486 yield Error(
487 object_path,
488 "cannot be subclassed at runtime, but isn't marked with @final in the stub",
489 stub,
490 runtime,
491 stub_desc=repr(stub),
492 )
493 except Exception:
494 # The class probably wants its subclasses to do something special.
495 # Examples: ctypes.Array, ctypes._SimpleCData
496 pass
497
498 # Runtime class might be annotated with `@final`:
499 try:
500 runtime_final = getattr(runtime, "__final__", False)
501 except Exception:
502 runtime_final = False
503
504 if runtime_final and not stub.is_final:
505 yield Error(
506 object_path,
507 "has `__final__` attribute, but isn't marked with @final in the stub",
508 stub,
509 runtime,
510 stub_desc=repr(stub),
511 )
512
513
514 SIZEOF_PYOBJECT = struct.calcsize("P")
515
516
517 def _shape_differs(t1: type[object], t2: type[object]) -> bool:
518 """Check whether two types differ in shape.
519
520 Mirrors the shape_differs() function in typeobject.c in CPython."""
521 if sys.version_info >= (3, 12):
522 return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__
523 else:
524 # CPython had more complicated logic before 3.12:
525 # https://github.com/python/cpython/blob/f3c6f882cddc8dc30320d2e73edf019e201394fc/Objects/typeobject.c#L2224
526 # We attempt to mirror it here well enough to support the most common cases.
527 if t1.__itemsize__ or t2.__itemsize__:
528 return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__
529 t_size = t1.__basicsize__
530 if not t2.__weakrefoffset__ and t1.__weakrefoffset__ + SIZEOF_PYOBJECT == t_size:
531 t_size -= SIZEOF_PYOBJECT
532 if not t2.__dictoffset__ and t1.__dictoffset__ + SIZEOF_PYOBJECT == t_size:
533 t_size -= SIZEOF_PYOBJECT
534 if not t2.__weakrefoffset__ and t2.__weakrefoffset__ == t_size:
535 t_size -= SIZEOF_PYOBJECT
536 return t_size != t2.__basicsize__
537
538
539 def _is_disjoint_base(typ: type[object]) -> bool:
540 """Return whether a type is a disjoint base at runtime, mirroring CPython's logic in typeobject.c.
541
542 See PEP 800."""
543 if typ is object:
544 return True
545 base = typ.__base__
546 assert base is not None, f"Type {typ} has no base"
547 return _shape_differs(typ, base)
548
549
550 def _verify_disjoint_base(
551 stub: nodes.TypeInfo, runtime: type[object], object_path: list[str]
552 ) -> Iterator[Error]:
553 is_disjoint_runtime = _is_disjoint_base(runtime)
554 # Don't complain about missing @disjoint_base if there are __slots__, because
555 # in that case we can infer that it's a disjoint base.
556 if (
557 is_disjoint_runtime
558 and not stub.is_disjoint_base
559 and not runtime.__dict__.get("__slots__")
560 and not stub.is_final
561 and not (stub.is_enum and stub.enum_members)
562 ):
563 yield Error(
564 object_path,
565 "is a disjoint base at runtime, but isn't marked with @disjoint_base in the stub",
566 stub,
567 runtime,
568 stub_desc=repr(stub),
569 )
570 elif stub.is_disjoint_base:
571 if not is_disjoint_runtime:
572 yield Error(
573 object_path,
574 "is marked with @disjoint_base in the stub, but isn't a disjoint base at runtime",
575 stub,
576 runtime,
577 stub_desc=repr(stub),
578 )
579 if runtime.__dict__.get("__slots__"):
580 yield Error(
581 object_path,
582 "is marked as @disjoint_base, but also has slots; add __slots__ instead",
583 stub,
584 runtime,
585 stub_desc=repr(stub),
586 )
587 elif stub.is_final:
588 yield Error(
589 object_path,
590 "is marked as @disjoint_base, but also marked as @final; remove @disjoint_base",
591 stub,
592 runtime,
593 stub_desc=repr(stub),
594 )
595 elif stub.is_enum and stub.enum_members:
596 yield Error(
597 object_path,
598 "is marked as @disjoint_base, but is an enum with members, which is implicitly final; "
599 "remove @disjoint_base",
600 stub,
601 runtime,
602 stub_desc=repr(stub),
603 )
604
605
606 def _verify_metaclass(
607 stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool
608 ) -> Iterator[Error]:
609 # We exclude protocols, because of how complex their implementation is in different versions of
610 # python. Enums are also hard, as are runtime TypedDicts; ignoring.
611 # TODO: check that metaclasses are identical?
612 if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict:
613 runtime_metaclass = type(runtime)
614 if runtime_metaclass is not type and stub.metaclass_type is None:
615 # This means that runtime has a custom metaclass, but a stub does not.
616 yield Error(
617 object_path,
618 "is inconsistent, metaclass differs",
619 stub,
620 runtime,
621 stub_desc="N/A",
622 runtime_desc=f"{runtime_metaclass}",
623 )
624 elif (
625 runtime_metaclass is type
626 and stub.metaclass_type is not None
627 # We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack.
628 # We also ignore `builtins.type` metaclass as an implementation detail in mypy.
629 and not mypy.types.is_named_instance(
630 stub.metaclass_type, ("abc.ABCMeta", "builtins.type")
631 )
632 ):
633 # This means that our stub has a metaclass that is not present at runtime.
634 yield Error(
635 object_path,
636 "metaclass mismatch",
637 stub,
638 runtime,
639 stub_desc=f"{stub.metaclass_type.type.fullname}",
640 runtime_desc="N/A",
641 )
642
643
644 @verify.register(nodes.TypeInfo)
645 def verify_typeinfo(
646 stub: nodes.TypeInfo,
647 runtime: MaybeMissing[type[Any]],
648 object_path: list[str],
649 *,
650 is_alias_target: bool = False,
651 ) -> Iterator[Error]:
652 if stub.is_type_check_only and not is_alias_target:
653 # This type only exists in stubs, we only check that the runtime part
654 # is missing. Other checks are not required.
655 if not isinstance(runtime, Missing):
656 yield Error(
657 object_path,
658 'is marked as "@type_check_only", but also exists at runtime',
659 stub,
660 runtime,
661 stub_desc=repr(stub),
662 )
663 return
664
665 if isinstance(runtime, Missing):
666 msg = "is not present at runtime"
667 if is_probably_private(stub.name):
668 msg += '. Maybe mark it as "@type_check_only"?'
669 yield Error(object_path, msg, stub, runtime, stub_desc=repr(stub))
670 return
671 if not isinstance(runtime, type):
672 # Yes, some runtime objects can be not types, no way to tell mypy about that.
673 yield Error(object_path, "is not a type", stub, runtime, stub_desc=repr(stub)) # type: ignore[unreachable]
674 return
675
676 yield from _verify_final(stub, runtime, object_path)
677 yield from _verify_disjoint_base(stub, runtime, object_path)
678 is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime)
679 yield from _verify_metaclass(
680 stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict
681 )
682
683 # Check everything already defined on the stub class itself (i.e. not inherited)
684 #
685 # Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things
686 # (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime,
687 # and exist purely for internal mypy reasons
688 to_check = {name for name in stub.names if name.isidentifier()}
689 # Check all public things on the runtime class
690 to_check.update(
691 m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS
692 )
693 # Special-case the __init__ method for Protocols and the __new__ method for TypedDicts
694 #
695 # TODO: On Python <3.11, __init__ methods on Protocol classes
696 # are silently discarded and replaced.
697 # However, this is not the case on Python 3.11+.
698 # Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+.
699 if stub.is_protocol:
700 to_check.discard("__init__")
701 if is_runtime_typeddict:
702 to_check.discard("__new__")
703
704 for entry in sorted(to_check):
705 mangled_entry = entry
706 if entry.startswith("__") and not entry.endswith("__"):
707 mangled_entry = f"_{stub.name.lstrip('_')}{entry}"
708 stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING)
709 assert stub_to_verify is not None
710 try:
711 try:
712 runtime_attr = getattr(runtime, mangled_entry)
713 except AttributeError:
714 runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)
715 except Exception:
716 # Catch all exceptions in case the runtime raises an unexpected exception
717 # from __getattr__ or similar.
718 continue
719
720 # If it came from the metaclass, consider the runtime_attr to be MISSING
721 # for a more accurate message
722 if (
723 runtime_attr is not MISSING
724 and type(runtime) is not runtime
725 and getattr(runtime_attr, "__objclass__", None) is type(runtime)
726 ):
727 runtime_attr = MISSING
728
729 # __setattr__ and __delattr__ on object are a special case,
730 # so if we only have these methods inherited from there, pretend that
731 # we don't have them. See python/typeshed#7385.
732 if (
733 entry in ("__setattr__", "__delattr__")
734 and runtime_attr is not MISSING
735 and runtime is not object
736 and getattr(runtime_attr, "__objclass__", None) is object
737 ):
738 runtime_attr = MISSING
739
740 # Do not error for an object missing from the stub
741 # If the runtime object is a types.WrapperDescriptorType object
742 # and has a non-special dunder name.
743 # The vast majority of these are false positives.
744 if not (
745 isinstance(stub_to_verify, Missing)
746 and isinstance(runtime_attr, types.WrapperDescriptorType)
747 and is_dunder(mangled_entry, exclude_special=True)
748 ):
749 yield from verify(stub_to_verify, runtime_attr, object_path + [entry])
750
751
752 def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]:
753 static_runtime = importlib.import_module(object_path[0])
754 for entry in object_path[1:]:
755 try:
756 static_runtime = inspect.getattr_static(static_runtime, entry)
757 except AttributeError:
758 # This can happen with mangled names, ignore for now.
759 # TODO: pass more information about ancestors of nodes/objects to verify, so we don't
760 # have to do this hacky lookup. Would be useful in several places.
761 return MISSING
762 return static_runtime
763
764
765 def _verify_static_class_methods(
766 stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str]
767 ) -> Iterator[str]:
768 if stub.name in ("__new__", "__init_subclass__", "__class_getitem__"):
769 # Special cased by Python, so don't bother checking
770 return
771 if inspect.isbuiltin(runtime):
772 # The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do
773 # something a little hacky that seems to work well
774 probably_class_method = isinstance(getattr(runtime, "__self__", None), type)
775 if probably_class_method and not stub.is_class:
776 yield "runtime is a classmethod but stub is not"
777 if not probably_class_method and stub.is_class:
778 yield "stub is a classmethod but runtime is not"
779 return
780
781 if static_runtime is MISSING:
782 return
783
784 if isinstance(static_runtime, classmethod) and not stub.is_class:
785 yield "runtime is a classmethod but stub is not"
786 if not isinstance(static_runtime, classmethod) and stub.is_class:
787 yield "stub is a classmethod but runtime is not"
788 if isinstance(static_runtime, staticmethod) and not stub.is_static:
789 yield "runtime is a staticmethod but stub is not"
790 if not isinstance(static_runtime, staticmethod) and stub.is_static:
791 yield "stub is a staticmethod but runtime is not"
792
793
794 def _verify_arg_name(
795 stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str
796 ) -> Iterator[str]:
797 """Checks whether argument names match."""
798 # Ignore exact names for most dunder methods
799 if is_dunder(function_name, exclude_special=True):
800 return
801
802 if (
803 stub_arg.variable.name == runtime_arg.name
804 or stub_arg.variable.name.removeprefix("__") == runtime_arg.name
805 ):
806 return
807
808 nonspecific_names = {"object", "args"}
809 if runtime_arg.name in nonspecific_names:
810 return
811
812 def names_approx_match(a: str, b: str) -> bool:
813 a = a.strip("_")
814 b = b.strip("_")
815 return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1
816
817 # Be more permissive about names matching for positional-only arguments
818 if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match(
819 stub_arg.variable.name, runtime_arg.name
820 ):
821 return
822 # This comes up with namedtuples, so ignore
823 if stub_arg.variable.name == "_self":
824 return
825 yield (
826 f'stub parameter "{stub_arg.variable.name}" '
827 f'differs from runtime parameter "{runtime_arg.name}"'
828 )
829
830
831 def _verify_arg_default_value(
832 stub_arg: nodes.Argument, runtime_arg: inspect.Parameter
833 ) -> Iterator[str]:
834 """Checks whether argument default values are compatible."""
835 if runtime_arg.default is not inspect.Parameter.empty:
836 if stub_arg.kind.is_required():
837 yield (
838 f'runtime parameter "{runtime_arg.name}" '
839 "has a default value but stub parameter does not"
840 )
841 else:
842 type_context = stub_arg.variable.type
843 runtime_type = get_mypy_type_of_runtime_value(
844 runtime_arg.default, type_context=type_context
845 )
846
847 # Fallback to the type annotation type if var type is missing. The type annotation
848 # is an UnboundType, but I don't know enough to know what the pros and cons here are.
849 # UnboundTypes have ugly question marks following them, so default to var type.
850 # Note we do this same fallback when constructing signatures in from_overloadedfuncdef
851 stub_type = stub_arg.variable.type or stub_arg.type_annotation
852 if isinstance(stub_type, mypy.types.TypeVarType):
853 stub_type = stub_type.upper_bound
854 if (
855 runtime_type is not None
856 and stub_type is not None
857 # Avoid false positives for marker objects
858 and type(runtime_arg.default) is not object
859 # And ellipsis
860 and runtime_arg.default is not ...
861 and not is_subtype_helper(runtime_type, stub_type)
862 ):
863 yield (
864 f'runtime parameter "{runtime_arg.name}" '
865 f"has a default value of type {runtime_type}, "
866 f"which is incompatible with stub parameter type {stub_type}"
867 )
868 if stub_arg.initializer is not None:
869 stub_default = evaluate_expression(stub_arg.initializer)
870 if (
871 stub_default is not UNKNOWN
872 and stub_default is not ...
873 and runtime_arg.default is not UNREPRESENTABLE
874 ):
875 defaults_match = True
876 # We want the types to match exactly, e.g. in case the stub has
877 # True and the runtime has 1 (or vice versa).
878 if type(stub_default) is not type(runtime_arg.default):
879 defaults_match = False
880 else:
881 try:
882 defaults_match = bool(stub_default == runtime_arg.default)
883 except Exception:
884 # Exception can be raised in bool dunder method (e.g. numpy arrays)
885 # At this point, consider the default to be different, it is probably
886 # too complex to put in a stub anyway.
887 defaults_match = False
888 if not defaults_match:
889 yield (
890 f'runtime parameter "{runtime_arg.name}" '
891 f"has a default value of {runtime_arg.default!r}, "
892 f"which is different from stub parameter default {stub_default!r}"
893 )
894 else:
895 if stub_arg.kind.is_optional():
896 yield (
897 f'stub parameter "{stub_arg.variable.name}" has a default value '
898 f"but runtime parameter does not"
899 )
900
901
902 def maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]:
903 if args and name in ("__init_subclass__", "__class_getitem__"):
904 # These are implicitly classmethods. If the stub chooses not to have @classmethod, we
905 # should remove the cls argument
906 if args[0].variable.name == "cls":
907 return args[1:]
908 return args
909
910
911 class Signature(Generic[T]):
912 def __init__(self) -> None:
913 self.pos: list[T] = []
914 self.kwonly: dict[str, T] = {}
915 self.varpos: T | None = None
916 self.varkw: T | None = None
917
918 def __str__(self) -> str:
919 def get_name(arg: Any) -> str:
920 if isinstance(arg, inspect.Parameter):
921 return arg.name
922 if isinstance(arg, nodes.Argument):
923 return arg.variable.name
924 raise AssertionError
925
926 def get_type(arg: Any) -> str | None:
927 if isinstance(arg, inspect.Parameter):
928 return None
929 if isinstance(arg, nodes.Argument):
930 return str(arg.variable.type or arg.type_annotation)
931 raise AssertionError
932
933 def has_default(arg: Any) -> bool:
934 if isinstance(arg, inspect.Parameter):
935 return arg.default is not inspect.Parameter.empty
936 if isinstance(arg, nodes.Argument):
937 return arg.kind.is_optional()
938 raise AssertionError
939
940 def get_desc(arg: Any) -> str:
941 arg_type = get_type(arg)
942 return (
943 get_name(arg)
944 + (f": {arg_type}" if arg_type else "")
945 + (" = ..." if has_default(arg) else "")
946 )
947
948 kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a)))
949 ret = "def ("
950 ret += ", ".join(
951 [get_desc(arg) for arg in self.pos]
952 + (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else []))
953 + [get_desc(arg) for arg in kw_only]
954 + (["**" + get_name(self.varkw)] if self.varkw else [])
955 )
956 ret += ")"
957 return ret
958
959 @staticmethod
960 def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]:
961 stub_sig: Signature[nodes.Argument] = Signature()
962 stub_args = maybe_strip_cls(stub.name, stub.arguments)
963 for stub_arg in stub_args:
964 if stub_arg.kind.is_positional():
965 stub_sig.pos.append(stub_arg)
966 elif stub_arg.kind.is_named():
967 stub_sig.kwonly[stub_arg.variable.name] = stub_arg
968 elif stub_arg.kind == nodes.ARG_STAR:
969 stub_sig.varpos = stub_arg
970 elif stub_arg.kind == nodes.ARG_STAR2:
971 if stub_arg.variable.type is not None and isinstance(
972 (typed_dict_arg := mypy.types.get_proper_type(stub_arg.variable.type)),
973 mypy.types.TypedDictType,
974 ):
975 for key_name, key_type in typed_dict_arg.items.items():
976 optional = key_name not in typed_dict_arg.required_keys
977 stub_sig.kwonly[key_name] = nodes.Argument(
978 nodes.Var(key_name, key_type),
979 type_annotation=key_type,
980 initializer=nodes.EllipsisExpr() if optional else None,
981 kind=nodes.ARG_NAMED_OPT if optional else nodes.ARG_NAMED,
982 pos_only=False,
983 )
984 else:
985 stub_sig.varkw = stub_arg
986 else:
987 raise AssertionError
988 return stub_sig
989
990 @staticmethod
991 def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]:
992 runtime_sig: Signature[inspect.Parameter] = Signature()
993 for runtime_arg in signature.parameters.values():
994 if runtime_arg.kind in (
995 inspect.Parameter.POSITIONAL_ONLY,
996 inspect.Parameter.POSITIONAL_OR_KEYWORD,
997 ):
998 runtime_sig.pos.append(runtime_arg)
999 elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY:
1000 runtime_sig.kwonly[runtime_arg.name] = runtime_arg
1001 elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL:
1002 runtime_sig.varpos = runtime_arg
1003 elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD:
1004 runtime_sig.varkw = runtime_arg
1005 else:
1006 raise AssertionError
1007 return runtime_sig
1008
1009 @staticmethod
1010 def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]:
1011 """Returns a Signature from an OverloadedFuncDef.
1012
1013 If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its
1014 items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we
1015 try and combine the overload's items into a single signature that is compatible with any
1016 lies it might try to tell.
1017
1018 """
1019 # For most dunder methods, just assume all args are positional-only
1020 assume_positional_only = is_dunder(stub.name, exclude_special=True)
1021
1022 is_arg_pos_only: defaultdict[str, set[bool]] = defaultdict(set)
1023 for func in map(_resolve_funcitem_from_decorator, stub.items):
1024 assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}"
1025 args = maybe_strip_cls(stub.name, func.arguments)
1026 for index, arg in enumerate(args):
1027 if (
1028 arg.variable.name.startswith("__")
1029 or arg.pos_only
1030 or assume_positional_only
1031 or arg.variable.name.strip("_") == "self"
1032 or (index == 0 and arg.variable.name.strip("_") == "cls")
1033 ):
1034 is_arg_pos_only[arg.variable.name].add(True)
1035 else:
1036 is_arg_pos_only[arg.variable.name].add(False)
1037
1038 all_args: dict[str, list[tuple[nodes.Argument, int]]] = {}
1039 for func in map(_resolve_funcitem_from_decorator, stub.items):
1040 assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}"
1041 args = maybe_strip_cls(stub.name, func.arguments)
1042 for index, arg in enumerate(args):
1043 # For positional-only args, we allow overloads to have different names for the same
1044 # argument. To accomplish this, we just make up a fake index-based name.
1045 # We can only use the index-based name if the argument is always
1046 # positional only. Sometimes overloads have an arg as positional-only
1047 # in some but not all branches of the overload.
1048 name = arg.variable.name
1049 if is_arg_pos_only[name] == {True}:
1050 name = f"__{index}"
1051
1052 all_args.setdefault(name, []).append((arg, index))
1053
1054 def get_position(arg_name: str) -> int:
1055 # We just need this to return the positional args in the correct order.
1056 return max(index for _, index in all_args[arg_name])
1057
1058 def get_type(arg_name: str) -> mypy.types.ProperType:
1059 with mypy.state.state.strict_optional_set(True):
1060 all_types = [
1061 arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name]
1062 ]
1063 return mypy.typeops.make_simplified_union([t for t in all_types if t])
1064
1065 def get_kind(arg_name: str) -> nodes.ArgKind:
1066 kinds = {arg.kind for arg, _ in all_args[arg_name]}
1067 if nodes.ARG_STAR in kinds:
1068 return nodes.ARG_STAR
1069 if nodes.ARG_STAR2 in kinds:
1070 return nodes.ARG_STAR2
1071 # The logic here is based on two tenets:
1072 # 1) If an arg is ever optional (or unspecified), it is optional
1073 # 2) If an arg is ever positional, it is positional
1074 is_opt = (
1075 len(all_args[arg_name]) < len(stub.items)
1076 or nodes.ARG_OPT in kinds
1077 or nodes.ARG_NAMED_OPT in kinds
1078 )
1079 is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds
1080 if is_opt:
1081 return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT
1082 return nodes.ARG_POS if is_pos else nodes.ARG_NAMED
1083
1084 sig: Signature[nodes.Argument] = Signature()
1085 for arg_name in sorted(all_args, key=get_position):
1086 # example_arg_name gives us a real name (in case we had a fake index-based name)
1087 example_arg_name = all_args[arg_name][0][0].variable.name
1088 arg = nodes.Argument(
1089 nodes.Var(example_arg_name, get_type(arg_name)),
1090 type_annotation=None,
1091 initializer=None,
1092 kind=get_kind(arg_name),
1093 pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]),
1094 )
1095 if arg.kind.is_positional():
1096 sig.pos.append(arg)
1097 elif arg.kind.is_named():
1098 sig.kwonly[arg.variable.name] = arg
1099 elif arg.kind == nodes.ARG_STAR:
1100 sig.varpos = arg
1101 elif arg.kind == nodes.ARG_STAR2:
1102 sig.varkw = arg
1103 else:
1104 raise AssertionError
1105 return sig
1106
1107
1108 def _verify_signature(
1109 stub: Signature[nodes.Argument],
1110 runtime: Signature[inspect.Parameter],
1111 function_name: str,
1112 warn_runtime_is_object_init: bool = False,
1113 ) -> Iterator[str]:
1114 # Check positional arguments match up
1115 for stub_arg, runtime_arg in zip(stub.pos, runtime.pos):
1116 yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
1117 yield from _verify_arg_default_value(stub_arg, runtime_arg)
1118 if (
1119 runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY
1120 and not stub_arg.pos_only
1121 and not stub_arg.variable.name.startswith("__")
1122 and stub_arg.variable.name.strip("_") != "self"
1123 and stub_arg.variable.name.strip("_") != "cls"
1124 ):
1125 yield (
1126 f'stub parameter "{stub_arg.variable.name}" should be positional-only '
1127 f'(add "/", e.g. "{runtime_arg.name}, /")'
1128 )
1129 if (
1130 runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY
1131 and (stub_arg.pos_only or stub_arg.variable.name.startswith("__"))
1132 and not runtime_arg.name.startswith("__")
1133 and stub_arg.variable.name.strip("_") != "self"
1134 and stub_arg.variable.name.strip("_") != "cls"
1135 and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods
1136 ):
1137 yield (
1138 f'stub parameter "{stub_arg.variable.name}" should be positional or keyword '
1139 '(remove "/")'
1140 )
1141
1142 # Check unmatched positional args
1143 if len(stub.pos) > len(runtime.pos):
1144 # There are cases where the stub exhaustively lists out the extra parameters the function
1145 # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the
1146 # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes
1147 # *args, since runtime logic may prevent arbitrary arguments from actually being accepted.
1148 if runtime.varpos is None:
1149 for stub_arg in stub.pos[len(runtime.pos) :]:
1150 # If the variable is in runtime.kwonly, it's just mislabelled as not a
1151 # keyword-only argument
1152 if stub_arg.variable.name not in runtime.kwonly:
1153 msg = f'runtime does not have parameter "{stub_arg.variable.name}"'
1154 if runtime.varkw is not None:
1155 msg += ". Maybe you forgot to make it keyword-only in the stub?"
1156 elif warn_runtime_is_object_init:
1157 msg += ". You may need to write stubs for __new__ instead of __init__."
1158 yield msg
1159 else:
1160 yield f'stub parameter "{stub_arg.variable.name}" is not keyword-only'
1161 if stub.varpos is not None:
1162 yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"'
1163 elif len(stub.pos) < len(runtime.pos):
1164 for runtime_arg in runtime.pos[len(stub.pos) :]:
1165 if runtime_arg.name not in stub.kwonly:
1166 if not _is_private_parameter(runtime_arg):
1167 yield f'stub does not have parameter "{runtime_arg.name}"'
1168 else:
1169 yield f'runtime parameter "{runtime_arg.name}" is not keyword-only'
1170
1171 # Checks involving *args
1172 if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None:
1173 if stub.varpos is None and runtime.varpos is not None:
1174 yield f'stub does not have *args parameter "{runtime.varpos.name}"'
1175 if stub.varpos is not None and runtime.varpos is None:
1176 yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"'
1177
1178 # Check keyword-only args
1179 for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)):
1180 stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg]
1181 yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
1182 yield from _verify_arg_default_value(stub_arg, runtime_arg)
1183
1184 # Check unmatched keyword-only args
1185 if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)):
1186 # There are cases where the stub exhaustively lists out the extra parameters the function
1187 # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't
1188 # exhaustively listed out params), we don't check whether the runtime has all of the stub's
1189 # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic
1190 # may prevent arbitrary keyword arguments from actually being accepted.
1191 for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)):
1192 if arg in {runtime_arg.name for runtime_arg in runtime.pos}:
1193 # Don't report this if we've reported it before
1194 if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}:
1195 yield f'runtime parameter "{arg}" is not keyword-only'
1196 else:
1197 msg = f'runtime does not have parameter "{arg}"'
1198 if warn_runtime_is_object_init:
1199 msg += ". You may need to write stubs for __new__ instead of __init__."
1200 yield msg
1201
1202 for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)):
1203 if arg in {stub_arg.variable.name for stub_arg in stub.pos}:
1204 # Don't report this if we've reported it before
1205 if not (
1206 runtime.varpos is None
1207 and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]}
1208 ):
1209 yield f'stub parameter "{arg}" is not keyword-only'
1210 else:
1211 if not _is_private_parameter(runtime.kwonly[arg]):
1212 yield f'stub does not have parameter "{arg}"'
1213
1214 # Checks involving **kwargs
1215 if stub.varkw is None and runtime.varkw is not None:
1216 # As mentioned above, don't enforce that the stub takes **kwargs.
1217 # Also check against positional parameters, to avoid a nitpicky message when an argument
1218 # isn't marked as keyword-only
1219 stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos}
1220 # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful
1221 if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names):
1222 yield f'stub does not have **kwargs parameter "{runtime.varkw.name}"'
1223 if stub.varkw is not None and runtime.varkw is None:
1224 yield f'runtime does not have **kwargs parameter "{stub.varkw.variable.name}"'
1225
1226
1227 def _is_private_parameter(arg: inspect.Parameter) -> bool:
1228 return (
1229 arg.name.startswith("_")
1230 and not arg.name.startswith("__")
1231 and arg.default is not inspect.Parameter.empty
1232 )
1233
1234
1235 @verify.register(nodes.FuncItem)
1236 def verify_funcitem(
1237 stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str]
1238 ) -> Iterator[Error]:
1239 if isinstance(runtime, Missing):
1240 yield Error(object_path, "is not present at runtime", stub, runtime)
1241 return
1242
1243 if not is_probably_a_function(runtime):
1244 yield Error(object_path, "is not a function", stub, runtime)
1245 if not callable(runtime):
1246 return
1247
1248 # Look the object up statically, to avoid binding by the descriptor protocol
1249 static_runtime = _static_lookup_runtime(object_path)
1250
1251 if isinstance(stub, nodes.FuncDef):
1252 for error_text in _verify_abstract_status(stub, runtime):
1253 yield Error(object_path, error_text, stub, runtime)
1254 for error_text in _verify_final_method(stub, runtime, static_runtime):
1255 yield Error(object_path, error_text, stub, runtime)
1256
1257 for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):
1258 yield Error(object_path, "is inconsistent, " + message, stub, runtime)
1259
1260 signature = safe_inspect_signature(runtime)
1261 runtime_is_coroutine = inspect.iscoroutinefunction(runtime)
1262
1263 if signature:
1264 stub_sig = Signature.from_funcitem(stub)
1265 runtime_sig = Signature.from_inspect_signature(signature)
1266 runtime_sig_desc = describe_runtime_callable(signature, is_async=runtime_is_coroutine)
1267 stub_desc = str(stub_sig)
1268 else:
1269 runtime_sig_desc, stub_desc = None, None
1270
1271 # Don't raise an error if the stub is a coroutine, but the runtime isn't.
1272 # That results in false positives.
1273 # See https://github.com/python/typeshed/issues/7344
1274 if runtime_is_coroutine and not stub.is_coroutine:
1275 yield Error(
1276 object_path,
1277 'is an "async def" function at runtime, but not in the stub',
1278 stub,
1279 runtime,
1280 stub_desc=stub_desc,
1281 runtime_desc=runtime_sig_desc,
1282 )
1283
1284 if not signature:
1285 return
1286
1287 for message in _verify_signature(
1288 stub_sig,
1289 runtime_sig,
1290 function_name=stub.name,
1291 warn_runtime_is_object_init=runtime is object.__init__,
1292 ):
1293 yield Error(
1294 object_path,
1295 "is inconsistent, " + message,
1296 stub,
1297 runtime,
1298 runtime_desc=runtime_sig_desc,
1299 )
1300
1301
1302 @verify.register(Missing)
1303 def verify_missing(
1304 stub: Missing, runtime: MaybeMissing[Any], object_path: list[str]
1305 ) -> Iterator[Error]:
1306 if runtime is MISSING:
1307 return
1308 yield Error(object_path, "is not present in stub", stub, runtime)
1309
1310
1311 @verify.register(nodes.Var)
1312 def verify_var(
1313 stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str]
1314 ) -> Iterator[Error]:
1315 if isinstance(runtime, Missing):
1316 # Don't always yield an error here, because we often can't find instance variables
1317 if len(object_path) <= 2:
1318 yield Error(object_path, "is not present at runtime", stub, runtime)
1319 return
1320
1321 if (
1322 stub.is_initialized_in_class
1323 and is_read_only_property(runtime)
1324 and (stub.is_settable_property or not stub.is_property)
1325 ):
1326 yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime)
1327
1328 runtime_type = get_mypy_type_of_runtime_value(runtime, type_context=stub.type)
1329 note = ""
1330 if (
1331 runtime_type is not None
1332 and stub.type is not None
1333 and not is_subtype_helper(runtime_type, stub.type)
1334 ):
1335 should_error = True
1336 # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd
1337 # annotate it with the type of runtime.value
1338 if isinstance(runtime, enum.Enum):
1339 runtime_type = get_mypy_type_of_runtime_value(runtime.value)
1340 if runtime_type is not None and is_subtype_helper(runtime_type, stub.type):
1341 should_error = False
1342 # We always allow setting the stub value to Ellipsis (...), but use
1343 # _value_ type as a fallback if given. If a member is ... and _value_
1344 # type is given, all runtime types should be assignable to _value_.
1345 proper_type = mypy.types.get_proper_type(stub.type)
1346 if (
1347 isinstance(proper_type, mypy.types.Instance)
1348 and proper_type.type.fullname in mypy.types.ELLIPSIS_TYPE_NAMES
1349 ):
1350 value_t = stub.info.get("_value_")
1351 if value_t is None or value_t.type is None or runtime_type is None:
1352 should_error = False
1353 elif is_subtype_helper(runtime_type, value_t.type):
1354 should_error = False
1355 else:
1356 note = " (incompatible '_value_')"
1357
1358 if should_error:
1359 yield Error(
1360 object_path,
1361 f"variable differs from runtime type {runtime_type}{note}",
1362 stub,
1363 runtime,
1364 )
1365 elif stub.final_value is not None and stub.final_value != runtime:
1366 yield Error(
1367 object_path,
1368 "is inconsistent, stub value for Final var differs from runtime value",
1369 stub,
1370 runtime,
1371 stub_desc=repr(stub.final_value),
1372 )
1373
1374
1375 @verify.register(nodes.OverloadedFuncDef)
1376 def verify_overloadedfuncdef(
1377 stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str]
1378 ) -> Iterator[Error]:
1379 # TODO: support `@type_check_only` decorator
1380 if isinstance(runtime, Missing):
1381 yield Error(object_path, "is not present at runtime", stub, runtime)
1382 return
1383
1384 if stub.is_property:
1385 # Any property with a setter is represented as an OverloadedFuncDef
1386 if is_read_only_property(runtime):
1387 yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime)
1388 return
1389
1390 if not is_probably_a_function(runtime):
1391 yield Error(object_path, "is not a function", stub, runtime)
1392 if not callable(runtime):
1393 return
1394
1395 # mypy doesn't allow overloads where one overload is abstract but another isn't,
1396 # so it should be okay to just check whether the first overload is abstract or not.
1397 #
1398 # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not;
1399 # and any property with a setter is represented as an OverloadedFuncDef internally;
1400 # not sure exactly what (if anything) we should do about that.
1401 first_part = stub.items[0]
1402 if isinstance(first_part, nodes.Decorator) and first_part.is_overload:
1403 for msg in _verify_abstract_status(first_part.func, runtime):
1404 yield Error(object_path, msg, stub, runtime)
1405
1406 # Look the object up statically, to avoid binding by the descriptor protocol
1407 static_runtime = _static_lookup_runtime(object_path)
1408
1409 for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):
1410 yield Error(object_path, "is inconsistent, " + message, stub, runtime)
1411
1412 # TODO: Should call _verify_final_method here,
1413 # but overloaded final methods in stubs cause a stubtest crash: see #14950
1414
1415 signature = safe_inspect_signature(runtime)
1416 if not signature:
1417 return
1418
1419 stub_sig = Signature.from_overloadedfuncdef(stub)
1420 runtime_sig = Signature.from_inspect_signature(signature)
1421
1422 for message in _verify_signature(
1423 stub_sig,
1424 runtime_sig,
1425 function_name=stub.name,
1426 warn_runtime_is_object_init=runtime is object.__init__,
1427 ):
1428 # TODO: This is a little hacky, but the addition here is super useful
1429 if "has a default value of type" in message:
1430 message += (
1431 ". This is often caused by overloads failing to account for explicitly passing "
1432 "in the default value."
1433 )
1434 yield Error(
1435 object_path,
1436 "is inconsistent, " + message,
1437 stub,
1438 runtime,
1439 stub_desc=(str(stub.type)) + f"\nInferred signature: {stub_sig}",
1440 runtime_desc="def " + str(signature),
1441 )
1442
1443
1444 @verify.register(nodes.TypeVarExpr)
1445 def verify_typevarexpr(
1446 stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str]
1447 ) -> Iterator[Error]:
1448 if isinstance(runtime, Missing):
1449 # We seem to insert these typevars into NamedTuple stubs, but they
1450 # don't exist at runtime. Just ignore!
1451 if stub.name == "_NT":
1452 return
1453 yield Error(object_path, "is not present at runtime", stub, runtime)
1454 return
1455 if not isinstance(runtime, TypeVar):
1456 yield Error(object_path, "is not a TypeVar", stub, runtime)
1457 return
1458
1459
1460 @verify.register(nodes.ParamSpecExpr)
1461 def verify_paramspecexpr(
1462 stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str]
1463 ) -> Iterator[Error]:
1464 if isinstance(runtime, Missing):
1465 yield Error(object_path, "is not present at runtime", stub, runtime)
1466 return
1467 maybe_paramspec_types = (
1468 getattr(typing, "ParamSpec", None),
1469 getattr(typing_extensions, "ParamSpec", None),
1470 )
1471 paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)
1472 if not paramspec_types or not isinstance(runtime, paramspec_types):
1473 yield Error(object_path, "is not a ParamSpec", stub, runtime)
1474 return
1475
1476
1477 def _is_django_cached_property(runtime: Any) -> bool: # pragma: no cover
1478 # This is a special case for
1479 # https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.functional.cached_property
1480 # This is needed in `django-stubs` project:
1481 # https://github.com/typeddjango/django-stubs
1482 if type(runtime).__name__ != "cached_property":
1483 return False
1484 try:
1485 return bool(runtime.func)
1486 except Exception:
1487 return False
1488
1489
1490 def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]:
1491 assert stub.func.is_property
1492 if isinstance(runtime, property):
1493 yield from _verify_final_method(stub.func, runtime.fget, MISSING)
1494 return
1495 if isinstance(runtime, functools.cached_property):
1496 yield from _verify_final_method(stub.func, runtime.func, MISSING)
1497 return
1498 if _is_django_cached_property(runtime):
1499 yield from _verify_final_method(stub.func, runtime.func, MISSING)
1500 return
1501 if inspect.isdatadescriptor(runtime):
1502 # It's enough like a property...
1503 return
1504 # Sometimes attributes pretend to be properties, for instance, to express that they
1505 # are read only. So allowlist if runtime_type matches the return type of stub.
1506 runtime_type = get_mypy_type_of_runtime_value(runtime)
1507 func_type = (
1508 stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None
1509 )
1510 if (
1511 runtime_type is not None
1512 and func_type is not None
1513 and is_subtype_helper(runtime_type, func_type)
1514 ):
1515 return
1516 yield "is inconsistent, cannot reconcile @property on stub with runtime object"
1517
1518
1519 def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]:
1520 stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT
1521 runtime_abstract = getattr(runtime, "__isabstractmethod__", False)
1522 # The opposite can exist: some implementations omit `@abstractmethod` decorators
1523 if runtime_abstract and not stub_abstract:
1524 item_type = "property" if stub.is_property else "method"
1525 yield f"is inconsistent, runtime {item_type} is abstract but stub is not"
1526
1527
1528 def _verify_final_method(
1529 stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any]
1530 ) -> Iterator[str]:
1531 if stub.is_final:
1532 return
1533 if getattr(runtime, "__final__", False) or (
1534 static_runtime is not MISSING and getattr(static_runtime, "__final__", False)
1535 ):
1536 yield "is decorated with @final at runtime, but not in the stub"
1537
1538
1539 def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None:
1540 """Returns a FuncItem that corresponds to the output of the decorator.
1541
1542 Returns None if we can't figure out what that would be. For convenience, this function also
1543 accepts FuncItems.
1544 """
1545 if isinstance(dec, nodes.FuncItem):
1546 return dec
1547 if dec.func.is_property:
1548 return None
1549
1550 def apply_decorator_to_funcitem(
1551 decorator: nodes.Expression, func: nodes.FuncItem
1552 ) -> nodes.FuncItem | None:
1553 if (
1554 isinstance(decorator, nodes.CallExpr)
1555 and isinstance(decorator.callee, nodes.RefExpr)
1556 and decorator.callee.fullname in mypy.types.DEPRECATED_TYPE_NAMES
1557 ):
1558 return func
1559 if not isinstance(decorator, nodes.RefExpr):
1560 return None
1561 if not decorator.fullname:
1562 # Happens with namedtuple
1563 return None
1564 if (
1565 decorator.fullname in ("builtins.staticmethod", "abc.abstractmethod")
1566 or decorator.fullname in mypy.types.OVERLOAD_NAMES
1567 or decorator.fullname in mypy.types.OVERRIDE_DECORATOR_NAMES
1568 or decorator.fullname in mypy.types.FINAL_DECORATOR_NAMES
1569 ):
1570 return func
1571 if decorator.fullname == "builtins.classmethod":
1572 if func.arguments[0].variable.name not in ("_cls", "cls", "mcs", "metacls"):
1573 raise StubtestFailure(
1574 f"unexpected class parameter name {func.arguments[0].variable.name!r} "
1575 f"in {dec.fullname}"
1576 )
1577 # FuncItem is written so that copy.copy() actually works, even when compiled
1578 ret = copy.copy(func)
1579 # Remove the cls argument, since it's not present in inspect.signature of classmethods
1580 ret.arguments = ret.arguments[1:]
1581 return ret
1582 # Just give up on any other decorators. After excluding properties, we don't run into
1583 # anything else when running on typeshed's stdlib.
1584 return None
1585
1586 func: nodes.FuncItem = dec.func
1587 for decorator in dec.original_decorators:
1588 resulting_func = apply_decorator_to_funcitem(decorator, func)
1589 if resulting_func is None:
1590 # We couldn't figure out how to apply the decorator by transforming nodes, so try to
1591 # reconstitute a FuncDef from the resulting type of the decorator
1592 # This is worse because e.g. we lose the values of defaults
1593 dec_type = mypy.types.get_proper_type(dec.type)
1594 callable_type = None
1595 if isinstance(dec_type, mypy.types.Instance):
1596 callable_type = mypy.subtypes.find_member(
1597 "__call__", dec_type, dec_type, is_operator=True
1598 )
1599 elif isinstance(dec_type, mypy.types.CallableType):
1600 callable_type = dec_type
1601
1602 callable_type = mypy.types.get_proper_type(callable_type)
1603 if isinstance(callable_type, mypy.types.CallableType):
1604 return _resolve_funcitem_from_callable_type(dec, callable_type)
1605 return None
1606
1607 func = resulting_func
1608 return func
1609
1610
1611 def _resolve_funcitem_from_callable_type(
1612 dec: nodes.Decorator, typ: mypy.types.CallableType
1613 ) -> nodes.FuncDef | None:
1614 if (
1615 typ.arg_kinds == [nodes.ARG_STAR, nodes.ARG_STAR2]
1616 and (var_arg := typ.var_arg()) is not None
1617 and isinstance(mypy.types.get_proper_type(var_arg.typ), mypy.types.AnyType)
1618 and (var_kwarg := typ.kw_arg()) is not None
1619 and isinstance(mypy.types.get_proper_type(var_kwarg.typ), mypy.types.AnyType)
1620 ):
1621 # There isn't a FuncDef we can invent corresponding to a Callable[..., T]
1622 return None
1623
1624 args: list[nodes.Argument] = []
1625 for i, (arg_type, arg_kind, arg_name) in enumerate(
1626 zip(typ.arg_types, typ.arg_kinds, typ.arg_names, strict=True)
1627 ):
1628 var_name = arg_name if arg_name is not None else f"__arg{i}"
1629 var = nodes.Var(var_name, arg_type)
1630 pos_only = arg_name is None and arg_kind == nodes.ARG_POS
1631 args.append(
1632 nodes.Argument(
1633 variable=var,
1634 type_annotation=arg_type,
1635 initializer=None, # CallableType doesn't store the values of defaults
1636 kind=arg_kind,
1637 pos_only=pos_only,
1638 )
1639 )
1640
1641 if dec.func.is_class:
1642 if not args:
1643 return None
1644 # Munge classmethods, similar to logic in _resolve_funcitem_from_decorator
1645 if args[0].variable.name not in ("_cls", "cls", "mcs", "metacls"):
1646 return None
1647 args.pop(0)
1648
1649 ret = nodes.FuncDef(name=typ.name or "", arguments=args, body=nodes.Block([]), typ=typ)
1650 ret.is_class = dec.func.is_class
1651 return ret
1652
1653
1654 @verify.register(nodes.Decorator)
1655 def verify_decorator(
1656 stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str]
1657 ) -> Iterator[Error]:
1658 if stub.func.is_type_check_only:
1659 # This function only exists in stubs, we only check that the runtime part
1660 # is missing. Other checks are not required.
1661 if not isinstance(runtime, Missing):
1662 yield Error(
1663 object_path,
1664 'is marked as "@type_check_only", but also exists at runtime',
1665 stub,
1666 runtime,
1667 stub_desc=repr(stub),
1668 )
1669 return
1670
1671 if isinstance(runtime, Missing):
1672 yield Error(object_path, "is not present at runtime", stub, runtime)
1673 return
1674 if stub.func.is_property:
1675 for message in _verify_readonly_property(stub, runtime):
1676 yield Error(object_path, message, stub, runtime)
1677 for message in _verify_abstract_status(stub.func, runtime):
1678 yield Error(object_path, message, stub, runtime)
1679 return
1680
1681 func = _resolve_funcitem_from_decorator(stub)
1682 if func is not None:
1683 yield from verify(func, runtime, object_path)
1684
1685
1686 @verify.register(nodes.TypeAlias)
1687 def verify_typealias(
1688 stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str]
1689 ) -> Iterator[Error]:
1690 stub_target = mypy.types.get_proper_type(stub.target)
1691 stub_desc = f"Type alias for {stub_target}"
1692 if isinstance(runtime, Missing):
1693 yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=stub_desc)
1694 return
1695 runtime_origin = get_origin(runtime) or runtime
1696 if isinstance(stub_target, mypy.types.Instance):
1697 if not isinstance(runtime_origin, type):
1698 yield Error(
1699 object_path,
1700 "is inconsistent, runtime is not a type",
1701 stub,
1702 runtime,
1703 stub_desc=stub_desc,
1704 )
1705 return
1706
1707 stub_origin = stub_target.type
1708 # Do our best to figure out the fullname of the runtime object...
1709 runtime_name: object
1710 try:
1711 runtime_name = runtime_origin.__qualname__
1712 except AttributeError:
1713 runtime_name = getattr(runtime_origin, "__name__", MISSING)
1714 if isinstance(runtime_name, str):
1715 runtime_module: object = getattr(runtime_origin, "__module__", MISSING)
1716 if isinstance(runtime_module, str):
1717 if runtime_module == "collections.abc" or (
1718 runtime_module == "re" and runtime_name in {"Match", "Pattern"}
1719 ):
1720 runtime_module = "typing"
1721 runtime_fullname = f"{runtime_module}.{runtime_name}"
1722 if re.fullmatch(rf"_?{re.escape(stub_origin.fullname)}", runtime_fullname):
1723 # Okay, we're probably fine.
1724 return
1725
1726 # Okay, either we couldn't construct a fullname
1727 # or the fullname of the stub didn't match the fullname of the runtime.
1728 # Fallback to a full structural check of the runtime vis-a-vis the stub.
1729 yield from verify_typeinfo(stub_origin, runtime_origin, object_path, is_alias_target=True)
1730 return
1731 if isinstance(stub_target, mypy.types.UnionType):
1732 # complain if runtime is not a Union or UnionType
1733 if runtime_origin is not Union and not isinstance(runtime, types.UnionType):
1734 yield Error(object_path, "is not a Union", stub, runtime, stub_desc=str(stub_target))
1735 # could check Union contents here...
1736 return
1737 if isinstance(stub_target, mypy.types.TupleType):
1738 if tuple not in getattr(runtime_origin, "__mro__", ()):
1739 yield Error(
1740 object_path, "is not a subclass of tuple", stub, runtime, stub_desc=stub_desc
1741 )
1742 # could check Tuple contents here...
1743 return
1744 if isinstance(stub_target, mypy.types.CallableType):
1745 if runtime_origin is not collections.abc.Callable:
1746 yield Error(
1747 object_path, "is not a type alias for Callable", stub, runtime, stub_desc=stub_desc
1748 )
1749 # could check Callable contents here...
1750 return
1751 if isinstance(stub_target, mypy.types.AnyType):
1752 return
1753 yield Error(object_path, "is not a recognised type alias", stub, runtime, stub_desc=stub_desc)
1754
1755
1756 # ====================
1757 # Helpers
1758 # ====================
1759
1760
1761 IGNORED_MODULE_DUNDERS: Final = frozenset(
1762 {
1763 "__file__",
1764 "__doc__",
1765 "__name__",
1766 "__builtins__",
1767 "__package__",
1768 "__cached__",
1769 "__loader__",
1770 "__spec__",
1771 "__annotations__",
1772 "__conditional_annotations__", # 3.14+
1773 "__annotate__",
1774 "__path__", # mypy adds __path__ to packages, but C packages don't have it
1775 "__getattr__", # resulting behaviour might be typed explicitly
1776 # Created by `warnings.warn`, does not make much sense to have in stubs:
1777 "__warningregistry__",
1778 # TODO: remove the following from this list
1779 "__author__",
1780 "__version__",
1781 "__copyright__",
1782 }
1783 )
1784
1785 IGNORABLE_CLASS_DUNDERS: Final = frozenset(
1786 {
1787 # Special attributes
1788 "__dict__",
1789 "__annotations__",
1790 "__annotate__",
1791 "__annotations_cache__",
1792 "__annotate_func__",
1793 "__text_signature__",
1794 "__weakref__",
1795 "__hash__",
1796 "__getattr__", # resulting behaviour might be typed explicitly
1797 "__setattr__", # defining this on a class can cause worse type checking
1798 "__vectorcalloffset__", # undocumented implementation detail of the vectorcall protocol
1799 "__firstlineno__",
1800 "__static_attributes__",
1801 "__classdictcell__",
1802 # isinstance/issubclass hooks that type-checkers don't usually care about
1803 "__instancecheck__",
1804 "__subclasshook__",
1805 "__subclasscheck__",
1806 # python2 only magic methods:
1807 "__cmp__",
1808 "__nonzero__",
1809 "__unicode__",
1810 "__div__",
1811 # cython methods
1812 "__pyx_vtable__",
1813 # Pickle methods
1814 "__setstate__",
1815 "__getstate__",
1816 "__getnewargs__",
1817 "__getinitargs__",
1818 "__reduce_ex__",
1819 "__reduce__",
1820 "__slotnames__", # Cached names of slots added by `copyreg` module.
1821 # ctypes weirdness
1822 "__ctype_be__",
1823 "__ctype_le__",
1824 "__ctypes_from_outparam__",
1825 # mypy limitations
1826 "__abstractmethods__", # Classes with metaclass=ABCMeta inherit this attribute
1827 "__new_member__", # If an enum defines __new__, the method is renamed as __new_member__
1828 "__dataclass_fields__", # Generated by dataclasses
1829 "__dataclass_params__", # Generated by dataclasses
1830 "__doc__", # mypy's semanal for namedtuples assumes this is str, not Optional[str]
1831 # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol)
1832 "__protocol_attrs__",
1833 "__callable_proto_members_only__",
1834 "__non_callable_proto_members__",
1835 # typing implementation details, consider removing some of these:
1836 "__parameters__",
1837 "__origin__",
1838 "__args__",
1839 "__orig_bases__",
1840 "__final__", # Has a specialized check
1841 # Consider removing __slots__?
1842 "__slots__",
1843 }
1844 )
1845
1846
1847 def is_probably_private(name: str) -> bool:
1848 return name.startswith("_") and not is_dunder(name)
1849
1850
1851 def is_probably_a_function(runtime: Any) -> bool:
1852 return (
1853 isinstance(
1854 runtime,
1855 (
1856 types.FunctionType,
1857 types.BuiltinFunctionType,
1858 types.MethodType,
1859 types.BuiltinMethodType,
1860 ),
1861 )
1862 or (inspect.ismethoddescriptor(runtime) and callable(runtime))
1863 or (isinstance(runtime, types.MethodWrapperType) and callable(runtime))
1864 )
1865
1866
1867 def is_read_only_property(runtime: object) -> bool:
1868 return isinstance(runtime, property) and runtime.fset is None and runtime.fdel is None
1869
1870
1871 def safe_inspect_signature(runtime: Any) -> inspect.Signature | None:
1872 if (
1873 hasattr(runtime, "__name__")
1874 and runtime.__name__ == "__init__"
1875 and hasattr(runtime, "__text_signature__")
1876 and runtime.__text_signature__ == "($self, /, *args, **kwargs)"
1877 and hasattr(runtime, "__objclass__")
1878 and hasattr(runtime.__objclass__, "__text_signature__")
1879 and runtime.__objclass__.__text_signature__ is not None
1880 ):
1881 # This is an __init__ method with the generic C-class signature.
1882 # In this case, the underlying class often has a better signature,
1883 # which we can convert into an __init__ signature by adding in the
1884 # self parameter.
1885 try:
1886 s = inspect.signature(runtime.__objclass__)
1887
1888 parameter_kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD
1889 if s.parameters:
1890 first_parameter = next(iter(s.parameters.values()))
1891 if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY:
1892 parameter_kind = inspect.Parameter.POSITIONAL_ONLY
1893 return s.replace(
1894 parameters=[inspect.Parameter("self", parameter_kind), *s.parameters.values()]
1895 )
1896 except Exception:
1897 pass
1898
1899 if (
1900 hasattr(runtime, "__name__")
1901 and runtime.__name__ == "__new__"
1902 and hasattr(runtime, "__text_signature__")
1903 and runtime.__text_signature__ == "($type, *args, **kwargs)"
1904 and hasattr(runtime, "__self__")
1905 and hasattr(runtime.__self__, "__text_signature__")
1906 and runtime.__self__.__text_signature__ is not None
1907 ):
1908 # This is a __new__ method with the generic C-class signature.
1909 # In this case, the underlying class often has a better signature,
1910 # which we can convert into a __new__ signature by adding in the
1911 # cls parameter.
1912
1913 # If the attached class has a valid __init__, skip recovering a
1914 # signature for this __new__ method.
1915 has_init = False
1916 if (
1917 hasattr(runtime.__self__, "__init__")
1918 and hasattr(runtime.__self__.__init__, "__objclass__")
1919 and runtime.__self__.__init__.__objclass__ is runtime.__self__
1920 ):
1921 has_init = True
1922
1923 if not has_init:
1924 try:
1925 s = inspect.signature(runtime.__self__)
1926 parameter_kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
1927 if s.parameters:
1928 first_parameter = next(iter(s.parameters.values()))
1929 if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY:
1930 parameter_kind = inspect.Parameter.POSITIONAL_ONLY
1931 return s.replace(
1932 parameters=[inspect.Parameter("cls", parameter_kind), *s.parameters.values()]
1933 )
1934 except Exception:
1935 pass
1936
1937 try:
1938 try:
1939 return inspect.signature(runtime)
1940 except ValueError:
1941 if (
1942 hasattr(runtime, "__text_signature__")
1943 and "<unrepresentable>" in runtime.__text_signature__
1944 ):
1945 # Try to fix up the signature. Workaround for
1946 # https://github.com/python/cpython/issues/87233
1947 sig = runtime.__text_signature__.replace("<unrepresentable>", "...")
1948 sig = inspect._signature_fromstr(inspect.Signature, runtime, sig) # type: ignore[attr-defined]
1949 assert isinstance(sig, inspect.Signature)
1950 new_params = [
1951 (
1952 parameter.replace(default=UNREPRESENTABLE)
1953 if parameter.default is ...
1954 else parameter
1955 )
1956 for parameter in sig.parameters.values()
1957 ]
1958 return sig.replace(parameters=new_params)
1959 else:
1960 raise
1961 except Exception:
1962 # inspect.signature throws ValueError all the time
1963 # catch RuntimeError because of https://bugs.python.org/issue39504
1964 # catch TypeError because of https://github.com/python/typeshed/pull/5762
1965 # catch AttributeError because of inspect.signature(_curses.window.border)
1966 return None
1967
1968
1969 def describe_runtime_callable(signature: inspect.Signature, *, is_async: bool) -> str:
1970 return f'{"async " if is_async else ""}def {signature}'
1971
1972
1973 class _TypeCheckOnlyBaseMapper(mypy.types.TypeTranslator):
1974 """Rewrites @type_check_only instances to the nearest runtime-visible base class."""
1975
1976 def visit_instance(self, t: mypy.types.Instance, /) -> mypy.types.Type:
1977 instance = mypy.types.get_proper_type(super().visit_instance(t))
1978 assert isinstance(instance, mypy.types.Instance)
1979
1980 if instance.type.is_type_check_only:
1981 # find the nearest non-@type_check_only base class
1982 for base_info in instance.type.mro[1:]:
1983 if not base_info.is_type_check_only:
1984 return map_instance_to_supertype(instance, base_info)
1985
1986 msg = f"all base classes of {instance.type.fullname!r} are @type_check_only"
1987 assert False, msg
1988
1989 return instance
1990
1991 def visit_type_alias_type(self, t: mypy.types.TypeAliasType, /) -> mypy.types.Type:
1992 return t
1993
1994
1995 _TYPE_CHECK_ONLY_BASE_MAPPER = _TypeCheckOnlyBaseMapper()
1996
1997
1998 def _relax_type_check_only_type(typ: mypy.types.ProperType) -> mypy.types.ProperType:
1999 return mypy.types.get_proper_type(typ.accept(_TYPE_CHECK_ONLY_BASE_MAPPER))
2000
2001
2002 def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool:
2003 """Checks whether ``left`` is a subtype of ``right``."""
2004 left = _relax_type_check_only_type(mypy.types.get_proper_type(left))
2005 right = _relax_type_check_only_type(mypy.types.get_proper_type(right))
2006 if (
2007 isinstance(left, mypy.types.LiteralType)
2008 and isinstance(left.value, int)
2009 and left.value in (0, 1)
2010 and mypy.types.is_named_instance(right, "builtins.bool")
2011 ):
2012 # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors.
2013 return True
2014
2015 if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance(
2016 left, "builtins.dict"
2017 ):
2018 # Special case checks against TypedDicts
2019 return True
2020
2021 with mypy.state.state.strict_optional_set(True):
2022 return mypy.subtypes.is_subtype(left, right)
2023
2024
2025 def get_mypy_node_for_name(module: str, type_name: str) -> mypy.nodes.SymbolNode | None:
2026 stub = get_stub(module)
2027 if stub is None:
2028 return None
2029 if type_name not in stub.names:
2030 return None
2031 return stub.names[type_name].node
2032
2033
2034 def get_mypy_type_of_runtime_value(
2035 runtime: Any, type_context: mypy.types.Type | None = None
2036 ) -> mypy.types.Type | None:
2037 """Returns a mypy type object representing the type of ``runtime``.
2038
2039 Returns None if we can't find something that works.
2040
2041 """
2042 if runtime is None:
2043 return mypy.types.NoneType()
2044 if isinstance(runtime, property):
2045 # Give up on properties to avoid issues with things that are typed as attributes.
2046 return None
2047
2048 def anytype() -> mypy.types.AnyType:
2049 return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated)
2050
2051 if isinstance(
2052 runtime,
2053 (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType),
2054 ):
2055 builtins = get_stub("builtins")
2056 assert builtins is not None
2057 type_info = builtins.names["function"].node
2058 assert isinstance(type_info, nodes.TypeInfo)
2059 fallback = mypy.types.Instance(type_info, [anytype()])
2060 signature = safe_inspect_signature(runtime)
2061 if signature:
2062 arg_types = []
2063 arg_kinds = []
2064 arg_names = []
2065 for arg in signature.parameters.values():
2066 arg_types.append(anytype())
2067 arg_names.append(
2068 None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name
2069 )
2070 no_default = arg.default is inspect.Parameter.empty
2071 if arg.kind == inspect.Parameter.POSITIONAL_ONLY:
2072 arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT)
2073 elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
2074 arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT)
2075 elif arg.kind == inspect.Parameter.KEYWORD_ONLY:
2076 arg_kinds.append(nodes.ARG_NAMED if no_default else nodes.ARG_NAMED_OPT)
2077 elif arg.kind == inspect.Parameter.VAR_POSITIONAL:
2078 arg_kinds.append(nodes.ARG_STAR)
2079 elif arg.kind == inspect.Parameter.VAR_KEYWORD:
2080 arg_kinds.append(nodes.ARG_STAR2)
2081 else:
2082 raise AssertionError
2083 else:
2084 arg_types = [anytype(), anytype()]
2085 arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2]
2086 arg_names = [None, None]
2087
2088 return mypy.types.CallableType(
2089 arg_types,
2090 arg_kinds,
2091 arg_names,
2092 ret_type=anytype(),
2093 fallback=fallback,
2094 is_ellipsis_args=True,
2095 )
2096
2097 skip_type_object_type = False
2098 if type_context:
2099 # Don't attempt to process the type object when context is generic
2100 # This is related to issue #3737
2101 type_context = mypy.types.get_proper_type(type_context)
2102 # Callable types with a generic return value
2103 if isinstance(type_context, mypy.types.CallableType):
2104 if isinstance(type_context.ret_type, mypy.types.TypeVarType):
2105 skip_type_object_type = True
2106 # Type[x] where x is generic
2107 if isinstance(type_context, mypy.types.TypeType):
2108 if isinstance(type_context.item, mypy.types.TypeVarType):
2109 skip_type_object_type = True
2110
2111 if isinstance(runtime, type) and not skip_type_object_type:
2112 # Try and look up a stub for the runtime object itself
2113 # The logic here is similar to ExpressionChecker.analyze_ref_expr
2114 type_info = get_mypy_node_for_name(runtime.__module__, runtime.__name__)
2115 if isinstance(type_info, nodes.TypeInfo):
2116 result = mypy.typeops.type_object_type(type_info)
2117 if mypy.checkexpr.is_type_type_context(type_context):
2118 # This is the type in a type[] expression, so substitute type
2119 # variables with Any.
2120 result = mypy.erasetype.erase_typevars(result)
2121 return result
2122
2123 # Try and look up a stub for the runtime object's type
2124 type_info = get_mypy_node_for_name(type(runtime).__module__, type(runtime).__name__)
2125 if type_info is None:
2126 return None
2127 if isinstance(type_info, nodes.Var):
2128 return type_info.type
2129 if not isinstance(type_info, nodes.TypeInfo):
2130 return None
2131
2132 if isinstance(runtime, tuple):
2133 # Special case tuples so we construct a valid mypy.types.TupleType
2134 optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime]
2135 items = [(i if i is not None else anytype()) for i in optional_items]
2136 fallback = mypy.types.Instance(type_info, [anytype()])
2137 return mypy.types.TupleType(items, fallback)
2138
2139 fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars])
2140 if type(runtime) != runtime.__class__:
2141 # Since `__class__` is redefined for an instance, we can't trust
2142 # its `isinstance` checks, it can be dynamic. See #20919
2143 return fallback
2144
2145 value: bool | int | str
2146 if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str):
2147 value = runtime.name
2148 elif isinstance(runtime, bytes):
2149 value = bytes_to_human_readable_repr(runtime)
2150 elif isinstance(runtime, (bool, int, str)):
2151 value = runtime
2152 else:
2153 return fallback
2154
2155 return mypy.types.LiteralType(value=value, fallback=fallback)
2156
2157
2158 # ====================
2159 # Build and entrypoint
2160 # ====================
2161
2162
2163 _all_stubs: dict[str, nodes.MypyFile] = {}
2164
2165
2166 def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]:
2167 """Uses mypy to construct stub objects for the given modules.
2168
2169 This sets global state that ``get_stub`` can access.
2170
2171 Returns all modules we might want to check. If ``find_submodules`` is False, this is equal
2172 to ``modules``.
2173
2174 :param modules: List of modules to build stubs for.
2175 :param options: Mypy options for finding and building stubs.
2176 :param find_submodules: Whether to attempt to find submodules of the given modules as well.
2177
2178 """
2179 data_dir = mypy.build.default_data_dir()
2180 search_path = mypy.modulefinder.compute_search_paths([], options, data_dir)
2181 find_module_cache = mypy.modulefinder.FindModuleCache(
2182 search_path, fscache=None, options=options
2183 )
2184
2185 all_modules = []
2186 sources = []
2187 for module in modules:
2188 all_modules.append(module)
2189 if not find_submodules:
2190 module_path = find_module_cache.find_module(module)
2191 if not isinstance(module_path, str):
2192 # test_module will yield an error later when it can't find stubs
2193 continue
2194 sources.append(mypy.modulefinder.BuildSource(module_path, module, None))
2195 else:
2196 found_sources = find_module_cache.find_modules_recursive(module)
2197 sources.extend(found_sources)
2198 # find submodules via mypy
2199 all_modules.extend(s.module for s in found_sources if s.module not in all_modules)
2200 # find submodules via pkgutil
2201 try:
2202 runtime = silent_import_module(module)
2203 all_modules.extend(
2204 m.name
2205 for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + ".")
2206 if m.name not in all_modules
2207 )
2208 except KeyboardInterrupt:
2209 raise
2210 except BaseException:
2211 pass
2212
2213 if sources:
2214 try:
2215 res = mypy.build.build(sources=sources, options=options)
2216 except mypy.errors.CompileError as e:
2217 raise StubtestFailure(f"failed mypy compile:\n{e}") from e
2218 if res.errors:
2219 raise StubtestFailure("mypy build errors:\n" + "\n".join(res.errors))
2220
2221 global _all_stubs
2222 _all_stubs = res.files
2223
2224 return all_modules
2225
2226
2227 def get_stub(module: str) -> nodes.MypyFile | None:
2228 """Returns a stub object for the given module, if we've built one."""
2229 return _all_stubs.get(module)
2230
2231
2232 def get_typeshed_stdlib_modules(
2233 custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None
2234 ) -> set[str]:
2235 """Returns a list of stdlib modules in typeshed (for current Python version)."""
2236 stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir)
2237 if version_info is None:
2238 version_info = sys.version_info[0:2]
2239
2240 def exists_in_version(module: str) -> bool:
2241 assert version_info is not None
2242 parts = module.split(".")
2243 for i in range(len(parts), 0, -1):
2244 current_module = ".".join(parts[:i])
2245 if current_module in stdlib_py_versions:
2246 minver, maxver = stdlib_py_versions[current_module]
2247 return version_info >= minver and (maxver is None or version_info <= maxver)
2248 return False
2249
2250 if custom_typeshed_dir:
2251 typeshed_dir = Path(custom_typeshed_dir)
2252 else:
2253 typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed"
2254 stdlib_dir = typeshed_dir / "stdlib"
2255
2256 modules: set[str] = set()
2257 for path in stdlib_dir.rglob("*.pyi"):
2258 if path.stem == "__init__":
2259 path = path.parent
2260 module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,))
2261 if exists_in_version(module):
2262 modules.add(module)
2263 return modules
2264
2265
2266 def get_importable_stdlib_modules() -> set[str]:
2267 """Return all importable stdlib modules at runtime."""
2268 importable_stdlib_modules: set[str] = set()
2269 for module_name in sys.stdlib_module_names:
2270 if module_name in ANNOYING_STDLIB_MODULES:
2271 continue
2272
2273 try:
2274 runtime = silent_import_module(module_name)
2275 except ImportError:
2276 continue
2277 else:
2278 importable_stdlib_modules.add(module_name)
2279
2280 try:
2281 # some stdlib modules (e.g. `nt`) don't have __path__ set...
2282 runtime_path = runtime.__path__
2283 runtime_name = runtime.__name__
2284 except AttributeError:
2285 continue
2286
2287 for submodule in pkgutil.walk_packages(runtime_path, runtime_name + "."):
2288 submodule_name = submodule.name
2289
2290 # There are many annoying *.__main__ stdlib modules,
2291 # and including stubs for them isn't really that useful anyway:
2292 # tkinter.__main__ opens a tkinter windows; unittest.__main__ raises SystemExit; etc.
2293 #
2294 # The idlelib.* submodules are similarly annoying in opening random tkinter windows,
2295 # and we're unlikely to ever add stubs for idlelib in typeshed
2296 # (see discussion in https://github.com/python/typeshed/pull/9193)
2297 #
2298 # test.* modules do weird things like raising exceptions in __del__ methods,
2299 # leading to unraisable exceptions being logged to the terminal
2300 # as a warning at the end of the stubtest run
2301 if submodule_name.endswith(".__main__") or submodule_name.startswith(
2302 ("idlelib.", "test.")
2303 ):
2304 continue
2305
2306 try:
2307 silent_import_module(submodule_name)
2308 except KeyboardInterrupt:
2309 raise
2310 # importing multiprocessing.popen_forkserver on Windows raises AttributeError...
2311 # some submodules also appear to raise SystemExit as well on some Python versions
2312 # (not sure exactly which)
2313 except BaseException:
2314 continue
2315 else:
2316 importable_stdlib_modules.add(submodule_name)
2317
2318 return importable_stdlib_modules
2319
2320
2321 def get_allowlist_entries(allowlist_file: str) -> Iterator[str]:
2322 def strip_comments(s: str) -> str:
2323 try:
2324 return s[: s.index("#")].strip()
2325 except ValueError:
2326 return s.strip()
2327
2328 with open(allowlist_file) as f:
2329 for line in f:
2330 entry = strip_comments(line)
2331 if entry:
2332 yield entry
2333
2334
2335 class _Arguments:
2336 modules: list[str]
2337 concise: bool
2338 ignore_missing_stub: bool
2339 ignore_positional_only: bool
2340 ignore_disjoint_bases: bool
2341 strict_type_check_only: bool
2342 allowlist: list[str]
2343 generate_allowlist: bool
2344 ignore_unused_allowlist: bool
2345 mypy_config_file: str | None
2346 custom_typeshed_dir: str | None
2347 check_typeshed: bool
2348 version: str
2349 show_traceback: bool
2350 pdb: bool
2351
2352
2353 # typeshed added a stub for __main__, but that causes stubtest to check itself
2354 ANNOYING_STDLIB_MODULES: Final = frozenset({"antigravity", "this", "__main__", "_ios_support"})
2355
2356
2357 def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int:
2358 """This is stubtest! It's time to test the stubs!"""
2359 # Load the allowlist. This is a series of strings corresponding to Error.object_desc
2360 # Values in the dict will store whether we used the allowlist entry or not.
2361 allowlist = {
2362 entry: False
2363 for allowlist_file in args.allowlist
2364 for entry in get_allowlist_entries(allowlist_file)
2365 }
2366 allowlist_regexes = {entry: re.compile(entry) for entry in allowlist}
2367
2368 # If we need to generate an allowlist, we store Error.object_desc for each error here.
2369 generated_allowlist = set()
2370
2371 modules = args.modules
2372 if args.check_typeshed:
2373 if args.modules:
2374 print(
2375 _style("error:", color="red", bold=True),
2376 "cannot pass both --check-typeshed and a list of modules",
2377 )
2378 return 1
2379 typeshed_modules = get_typeshed_stdlib_modules(args.custom_typeshed_dir)
2380 runtime_modules = get_importable_stdlib_modules()
2381 modules = sorted((typeshed_modules | runtime_modules) - ANNOYING_STDLIB_MODULES)
2382
2383 if not modules:
2384 print(_style("error:", color="red", bold=True), "no modules to check")
2385 return 1
2386
2387 options = Options()
2388 options.incremental = False
2389 options.custom_typeshed_dir = args.custom_typeshed_dir
2390 if options.custom_typeshed_dir:
2391 options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir)
2392 options.config_file = args.mypy_config_file
2393 options.use_builtins_fixtures = use_builtins_fixtures
2394 options.show_traceback = args.show_traceback
2395 options.pdb = args.pdb
2396 options.pos_only_special_methods = False
2397
2398 if options.config_file:
2399
2400 def set_strict_flags() -> None: # not needed yet
2401 return
2402
2403 parse_config_file(options, set_strict_flags, options.config_file, sys.stdout, sys.stderr)
2404
2405 def error_callback(msg: str) -> typing.NoReturn:
2406 print(_style("error:", color="red", bold=True), msg)
2407 sys.exit(1)
2408
2409 def warning_callback(msg: str) -> None:
2410 print(_style("warning:", color="yellow", bold=True), msg)
2411
2412 options.process_error_codes(error_callback=error_callback)
2413 options.process_incomplete_features(
2414 error_callback=error_callback, warning_callback=warning_callback
2415 )
2416 options.process_strict_bytes()
2417
2418 try:
2419 modules = build_stubs(modules, options, find_submodules=not args.check_typeshed)
2420 except StubtestFailure as stubtest_failure:
2421 print(
2422 _style("error:", color="red", bold=True),
2423 f"not checking stubs due to {stubtest_failure}",
2424 )
2425 return 1
2426
2427 exit_code = 0
2428 error_count = 0
2429 for module in modules:
2430 for error in test_module(module):
2431 # Filter errors
2432 if args.ignore_missing_stub and error.is_missing_stub():
2433 continue
2434 if args.ignore_positional_only and error.is_positional_only_related():
2435 continue
2436 if args.ignore_disjoint_bases and error.is_disjoint_base_related():
2437 continue
2438 if not args.strict_type_check_only and error.is_private_type_check_only_related():
2439 continue
2440 if error.object_desc in allowlist:
2441 allowlist[error.object_desc] = True
2442 continue
2443 is_allowlisted = False
2444 for w in allowlist:
2445 if allowlist_regexes[w].fullmatch(error.object_desc):
2446 allowlist[w] = True
2447 is_allowlisted = True
2448 break
2449 if is_allowlisted:
2450 continue
2451
2452 # We have errors, so change exit code, and output whatever necessary
2453 exit_code = 1
2454 if args.generate_allowlist:
2455 generated_allowlist.add(error.object_desc)
2456 continue
2457 safe_print(error.get_description(concise=args.concise))
2458 error_count += 1
2459
2460 # Print unused allowlist entries
2461 if not args.ignore_unused_allowlist:
2462 for w in allowlist:
2463 # Don't consider an entry unused if it regex-matches the empty string
2464 # This lets us allowlist errors that don't manifest at all on some systems
2465 if not allowlist[w] and not allowlist_regexes[w].fullmatch(""):
2466 exit_code = 1
2467 error_count += 1
2468 print(f"note: unused allowlist entry {w}")
2469
2470 # Print the generated allowlist
2471 if args.generate_allowlist:
2472 for e in sorted(generated_allowlist):
2473 print(e)
2474 exit_code = 0
2475 elif not args.concise:
2476 if error_count:
2477 print(
2478 _style(
2479 f"Found {error_count} error{plural_s(error_count)}"
2480 f" (checked {len(modules)} module{plural_s(modules)})",
2481 color="red",
2482 bold=True,
2483 )
2484 )
2485 else:
2486 print(
2487 _style(
2488 f"Success: no issues found in {len(modules)} module{plural_s(modules)}",
2489 color="green",
2490 bold=True,
2491 )
2492 )
2493
2494 return exit_code
2495
2496
2497 def safe_print(text: str) -> None:
2498 """Print a text replacing chars not representable in stdout encoding."""
2499 # If `sys.stdout` encoding is not the same as out (usually UTF8) string,
2500 # if may cause painful crashes. I don't want to reconfigure `sys.stdout`
2501 # to do `errors = "replace"` as that sounds scary.
2502 out_encoding = sys.stdout.encoding
2503 if out_encoding is not None:
2504 # Can be None if stdout is replaced (including our own tests). This should be
2505 # safe to omit if the actual stream doesn't care about encoding.
2506 text = text.encode(out_encoding, errors="replace").decode(out_encoding, errors="replace")
2507 print(text)
2508
2509
2510 def parse_options(args: list[str]) -> _Arguments:
2511 parser = argparse.ArgumentParser(
2512 description="Compares stubs to objects introspected from the runtime."
2513 )
2514 parser.add_argument("modules", nargs="*", help="Modules to test")
2515 parser.add_argument(
2516 "--concise",
2517 action="store_true",
2518 help="Makes stubtest's output more concise, one line per error",
2519 )
2520 parser.add_argument(
2521 "--ignore-missing-stub",
2522 action="store_true",
2523 help="Ignore errors for stub missing things that are present at runtime",
2524 )
2525 parser.add_argument(
2526 "--ignore-positional-only",
2527 action="store_true",
2528 help="Ignore errors for whether an argument should or shouldn't be positional-only",
2529 )
2530 # TODO: Remove once PEP 800 is accepted
2531 parser.add_argument(
2532 "--ignore-disjoint-bases",
2533 action="store_true",
2534 help="Disable checks for PEP 800 @disjoint_base classes",
2535 )
2536 parser.add_argument(
2537 "--strict-type-check-only",
2538 action="store_true",
2539 help="Require @type_check_only on private types that are not present at runtime",
2540 )
2541 parser.add_argument(
2542 "--allowlist",
2543 "--whitelist",
2544 action="append",
2545 metavar="FILE",
2546 default=[],
2547 help=(
2548 "Use file as an allowlist. Can be passed multiple times to combine multiple "
2549 "allowlists. Allowlists can be created with --generate-allowlist. Allowlists "
2550 "support regular expressions."
2551 ),
2552 )
2553 parser.add_argument(
2554 "--generate-allowlist",
2555 "--generate-whitelist",
2556 action="store_true",
2557 help="Print an allowlist (to stdout) to be used with --allowlist",
2558 )
2559 parser.add_argument(
2560 "--ignore-unused-allowlist",
2561 "--ignore-unused-whitelist",
2562 action="store_true",
2563 help="Ignore unused allowlist entries",
2564 )
2565 parser.add_argument(
2566 "--mypy-config-file",
2567 metavar="FILE",
2568 help=("Use specified mypy config file to determine mypy plugins and mypy path"),
2569 )
2570 parser.add_argument(
2571 "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR"
2572 )
2573 parser.add_argument(
2574 "--check-typeshed", action="store_true", help="Check all stdlib modules in typeshed"
2575 )
2576 parser.add_argument(
2577 "--version", action="version", version="%(prog)s " + mypy.version.__version__
2578 )
2579 parser.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error")
2580 parser.add_argument(
2581 "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error"
2582 )
2583
2584 return parser.parse_args(args, namespace=_Arguments())
2585
2586
2587 def main() -> int:
2588 mypy.util.check_python_version("stubtest")
2589 return test_stubs(parse_options(sys.argv[1:]))
2590
2591
2592 if __name__ == "__main__":
2593 sys.exit(main())