Debian Codegraph @

mypy/stubgenc.py

raw
1 #!/usr/bin/env python3
2 """Stub generator for C modules.
3
4 The public interface is via the mypy.stubgen module.
5 """
6
7 from __future__ import annotations
8
9 import enum
10 import glob
11 import importlib
12 import inspect
13 import keyword
14 import os.path
15 from collections.abc import Callable, Mapping
16 from types import FunctionType, ModuleType
17 from typing import Any
18
19 from mypy.fastparse import parse_type_comment
20 from mypy.moduleinspect import is_c_module
21 from mypy.stubdoc import (
22 ArgSig,
23 FunctionSig,
24 Sig,
25 find_unique_signatures,
26 infer_arg_sig_from_anon_docstring,
27 infer_prop_type_from_docstring,
28 infer_ret_type_sig_from_anon_docstring,
29 infer_ret_type_sig_from_docstring,
30 infer_sig_from_docstring,
31 parse_all_signatures,
32 )
33 from mypy.stubutil import (
34 BaseStubGenerator,
35 ClassInfo,
36 FunctionContext,
37 SignatureGenerator,
38 infer_method_arg_types,
39 infer_method_ret_type,
40 )
41 from mypy.util import quote_docstring
42
43
44 class ExternalSignatureGenerator(SignatureGenerator):
45 def __init__(
46 self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None
47 ) -> None:
48 """
49 Takes a mapping of function/method names to signatures and class name to
50 class signatures (usually corresponds to __init__).
51 """
52 self.func_sigs = func_sigs or {}
53 self.class_sigs = class_sigs or {}
54
55 @classmethod
56 def from_doc_dir(cls, doc_dir: str) -> ExternalSignatureGenerator:
57 """Instantiate from a directory of .rst files."""
58 all_sigs: list[Sig] = []
59 all_class_sigs: list[Sig] = []
60 for path in glob.glob(f"{doc_dir}/*.rst"):
61 with open(path) as f:
62 loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines())
63 all_sigs += loc_sigs
64 all_class_sigs += loc_class_sigs
65 sigs = dict(find_unique_signatures(all_sigs))
66 class_sigs = dict(find_unique_signatures(all_class_sigs))
67 return ExternalSignatureGenerator(sigs, class_sigs)
68
69 def get_function_sig(
70 self, default_sig: FunctionSig, ctx: FunctionContext
71 ) -> list[FunctionSig] | None:
72 # method:
73 if (
74 ctx.class_info
75 and ctx.name in ("__new__", "__init__")
76 and ctx.name not in self.func_sigs
77 and ctx.class_info.name in self.class_sigs
78 ):
79 return [
80 FunctionSig(
81 name=ctx.name,
82 args=infer_arg_sig_from_anon_docstring(self.class_sigs[ctx.class_info.name]),
83 ret_type=infer_method_ret_type(ctx.name),
84 )
85 ]
86
87 # function:
88 if ctx.name not in self.func_sigs:
89 return None
90
91 inferred = [
92 FunctionSig(
93 name=ctx.name,
94 args=infer_arg_sig_from_anon_docstring(self.func_sigs[ctx.name]),
95 ret_type=None,
96 )
97 ]
98 if ctx.class_info:
99 return self.remove_self_type(inferred, ctx.class_info.self_var)
100 else:
101 return inferred
102
103 def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:
104 return None
105
106
107 class DocstringSignatureGenerator(SignatureGenerator):
108 def get_function_sig(
109 self, default_sig: FunctionSig, ctx: FunctionContext
110 ) -> list[FunctionSig] | None:
111 inferred = infer_sig_from_docstring(ctx.docstring, ctx.name)
112 if inferred:
113 assert ctx.docstring is not None
114 if is_pybind11_overloaded_function_docstring(ctx.docstring, ctx.name):
115 # Remove pybind11 umbrella (*args, **kwargs) for overloaded functions
116 del inferred[-1]
117
118 if ctx.class_info:
119 if not inferred and ctx.name == "__init__":
120 # look for class-level constructor signatures of the form <class_name>(<signature>)
121 inferred = infer_sig_from_docstring(ctx.class_info.docstring, ctx.class_info.name)
122 if inferred:
123 inferred = [sig._replace(name="__init__") for sig in inferred]
124 return self.remove_self_type(inferred, ctx.class_info.self_var)
125 else:
126 return inferred
127
128 def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:
129 """Infer property type from docstring or docstring signature."""
130 if ctx.docstring is not None:
131 inferred = infer_ret_type_sig_from_anon_docstring(ctx.docstring)
132 if inferred:
133 return inferred
134 inferred = infer_ret_type_sig_from_docstring(ctx.docstring, ctx.name)
135 if inferred:
136 return inferred
137 inferred = infer_prop_type_from_docstring(ctx.docstring)
138 return inferred
139 else:
140 return None
141
142
143 def is_pybind11_overloaded_function_docstring(docstring: str, name: str) -> bool:
144 return docstring.startswith(f"{name}(*args, **kwargs)\nOverloaded function.\n\n")
145
146
147 def generate_stub_for_c_module(
148 module_name: str,
149 target: str,
150 known_modules: list[str],
151 doc_dir: str = "",
152 *,
153 include_private: bool = False,
154 export_less: bool = False,
155 include_docstrings: bool = False,
156 ) -> None:
157 """Generate stub for C module.
158
159 Signature generators are called in order until a list of signatures is returned. The order
160 is:
161 - signatures inferred from .rst documentation (if given)
162 - simple runtime introspection (looking for docstrings and attributes
163 with simple builtin types)
164 - fallback based special method names or "(*args, **kwargs)"
165
166 If directory for target doesn't exist it will be created. Existing stub
167 will be overwritten.
168 """
169 subdir = os.path.dirname(target)
170 if subdir and not os.path.isdir(subdir):
171 os.makedirs(subdir)
172
173 gen = InspectionStubGenerator(
174 module_name,
175 known_modules,
176 doc_dir,
177 include_private=include_private,
178 export_less=export_less,
179 include_docstrings=include_docstrings,
180 )
181 gen.generate_module()
182 output = gen.output()
183
184 with open(target, "w", encoding="utf-8") as file:
185 file.write(output)
186
187
188 class CFunctionStub:
189 """
190 Class that mimics a C function in order to provide parseable docstrings.
191 """
192
193 def __init__(self, name: str, doc: str, is_abstract: bool = False) -> None:
194 self.__name__ = name
195 self.__doc__ = doc
196 self.__abstractmethod__ = is_abstract
197
198 @classmethod
199 def _from_sig(cls, sig: FunctionSig, is_abstract: bool = False) -> CFunctionStub:
200 return CFunctionStub(sig.name, sig.format_sig()[:-4], is_abstract)
201
202 @classmethod
203 def _from_sigs(cls, sigs: list[FunctionSig], is_abstract: bool = False) -> CFunctionStub:
204 return CFunctionStub(
205 sigs[0].name, "\n".join(sig.format_sig()[:-4] for sig in sigs), is_abstract
206 )
207
208 def __get__(self) -> None: # noqa: PLE0302
209 """
210 This exists to make this object look like a method descriptor and thus
211 return true for CStubGenerator.ismethod()
212 """
213 pass
214
215
216 _Missing = enum.Enum("_Missing", "VALUE")
217
218
219 class InspectionStubGenerator(BaseStubGenerator):
220 """Stub generator that does not parse code.
221
222 Generation is performed by inspecting the module's contents, and thus works
223 for highly dynamic modules, pyc files, and C modules (via the CStubGenerator
224 subclass).
225 """
226
227 def __init__(
228 self,
229 module_name: str,
230 known_modules: list[str],
231 doc_dir: str = "",
232 _all_: list[str] | None = None,
233 include_private: bool = False,
234 export_less: bool = False,
235 include_docstrings: bool = False,
236 module: ModuleType | None = None,
237 ) -> None:
238 self.doc_dir = doc_dir
239 if module is None:
240 self.module = importlib.import_module(module_name)
241 else:
242 self.module = module
243 self.is_c_module = is_c_module(self.module)
244 self.known_modules = known_modules
245 self.resort_members = self.is_c_module
246 super().__init__(_all_, include_private, export_less, include_docstrings)
247 self.module_name = module_name
248 if self.is_c_module:
249 # Add additional implicit imports.
250 # C-extensions are given more latitude since they do not import the typing module.
251 self.known_imports.update(
252 {
253 "typing": [
254 "Any",
255 "Callable",
256 "ClassVar",
257 "Dict",
258 "Iterable",
259 "Iterator",
260 "List",
261 "Literal",
262 "NamedTuple",
263 "Optional",
264 "Tuple",
265 "Union",
266 ]
267 }
268 )
269
270 def get_default_function_sig(self, func: object, ctx: FunctionContext) -> FunctionSig:
271 argspec = None
272 if not self.is_c_module:
273 # Get the full argument specification of the function
274 try:
275 argspec = inspect.getfullargspec(func)
276 except TypeError:
277 # some callables cannot be inspected, e.g. functools.partial
278 pass
279 if argspec is None:
280 if ctx.class_info is not None:
281 # method:
282 return FunctionSig(
283 name=ctx.name,
284 args=infer_c_method_args(ctx.name, ctx.class_info.self_var),
285 ret_type=infer_method_ret_type(ctx.name),
286 )
287 else:
288 # function:
289 return FunctionSig(
290 name=ctx.name,
291 args=[ArgSig(name="*args"), ArgSig(name="**kwargs")],
292 ret_type=None,
293 )
294
295 # Extract the function arguments, defaults, and varargs
296 args = argspec.args
297 defaults = argspec.defaults
298 varargs = argspec.varargs
299 kwargs = argspec.varkw
300 annotations = argspec.annotations
301 kwonlyargs = argspec.kwonlyargs
302 kwonlydefaults = argspec.kwonlydefaults
303
304 def get_annotation(key: str) -> str | None:
305 if key not in annotations:
306 return None
307 argtype = annotations[key]
308 if argtype is None:
309 return "None"
310 if not isinstance(argtype, str):
311 return self.get_type_fullname(argtype)
312 return argtype
313
314 arglist: list[ArgSig] = []
315
316 # Add the arguments to the signature
317 def add_args(
318 args: list[str], get_default_value: Callable[[int, str], object | _Missing]
319 ) -> None:
320 for i, arg in enumerate(args):
321 # Check if the argument has a default value
322 default_value = get_default_value(i, arg)
323 if default_value is not _Missing.VALUE:
324 if arg in annotations:
325 argtype = get_annotation(arg)
326 else:
327 argtype = self.get_type_annotation(default_value)
328 if argtype == "None":
329 # None is not a useful annotation, but we can infer that the arg
330 # is optional
331 incomplete = self.add_name("_typeshed.Incomplete")
332 argtype = f"{incomplete} | None"
333
334 arglist.append(ArgSig(arg, argtype, default=True))
335 else:
336 arglist.append(ArgSig(arg, get_annotation(arg), default=False))
337
338 def get_pos_default(i: int, _arg: str) -> Any | _Missing:
339 if defaults and i >= len(args) - len(defaults):
340 return defaults[i - (len(args) - len(defaults))]
341 else:
342 return _Missing.VALUE
343
344 add_args(args, get_pos_default)
345
346 # Add *args if present
347 if varargs:
348 arglist.append(ArgSig(f"*{varargs}", get_annotation(varargs)))
349 # if we have keyword only args, then we need to add "*"
350 elif kwonlyargs:
351 arglist.append(ArgSig("*"))
352
353 def get_kw_default(_i: int, arg: str) -> Any | _Missing:
354 if kwonlydefaults and arg in kwonlydefaults:
355 return kwonlydefaults[arg]
356 else:
357 return _Missing.VALUE
358
359 add_args(kwonlyargs, get_kw_default)
360
361 # Add **kwargs if present
362 if kwargs:
363 arglist.append(ArgSig(f"**{kwargs}", get_annotation(kwargs)))
364
365 # add types for known special methods
366 if ctx.class_info is not None and all(
367 arg.type is None and arg.default is False for arg in arglist
368 ):
369 new_args = infer_method_arg_types(
370 ctx.name, ctx.class_info.self_var, [arg.name for arg in arglist if arg.name]
371 )
372 if new_args is not None:
373 arglist = new_args
374
375 ret_type = get_annotation("return") or infer_method_ret_type(ctx.name)
376 return FunctionSig(ctx.name, arglist, ret_type)
377
378 def get_sig_generators(self) -> list[SignatureGenerator]:
379 if not self.is_c_module:
380 return []
381 else:
382 sig_generators: list[SignatureGenerator] = [DocstringSignatureGenerator()]
383 if self.doc_dir:
384 # Collect info from docs (if given). Always check these first.
385 sig_generators.insert(0, ExternalSignatureGenerator.from_doc_dir(self.doc_dir))
386 return sig_generators
387
388 def strip_or_import(self, type_name: str) -> str:
389 """Strips unnecessary module names from typ.
390
391 If typ represents a type that is inside module or is a type coming from builtins, remove
392 module declaration from it. Return stripped name of the type.
393
394 Arguments:
395 typ: name of the type
396 """
397 local_modules = ["builtins", self.module_name]
398 parsed_type = parse_type_comment(type_name, 0, 0, None)[1]
399 assert parsed_type is not None, type_name
400 return self.print_annotation(parsed_type, self.known_modules, local_modules)
401
402 def get_obj_module(self, obj: object) -> str | None:
403 """Return module name of the object."""
404 return getattr(obj, "__module__", None)
405
406 def is_defined_in_module(self, obj: object) -> bool:
407 """Check if object is considered defined in the current module."""
408 module = self.get_obj_module(obj)
409 return module is None or module == self.module_name
410
411 def generate_module(self) -> None:
412 all_items = self.get_members(self.module)
413 if self.resort_members:
414 all_items = sorted(all_items, key=lambda x: x[0])
415 items = []
416 for name, obj in all_items:
417 if inspect.ismodule(obj) and obj.__name__ in self.known_modules:
418 module_name = obj.__name__
419 if module_name.startswith(self.module_name + "."):
420 # from {.rel_name} import {mod_name} as {name}
421 pkg_name, mod_name = module_name.rsplit(".", 1)
422 rel_module = pkg_name[len(self.module_name) :] or "."
423 self.import_tracker.add_import_from(rel_module, [(mod_name, name)])
424 self.import_tracker.reexport(name)
425 else:
426 # import {module_name} as {name}
427 self.import_tracker.add_import(module_name, name)
428 self.import_tracker.reexport(name)
429 elif self.is_defined_in_module(obj) and not inspect.ismodule(obj):
430 # process this below
431 items.append((name, obj))
432 else:
433 # from {obj_module} import {obj_name}
434 obj_module_name = self.get_obj_module(obj)
435 if obj_module_name:
436 self.import_tracker.add_import_from(obj_module_name, [(name, None)])
437 if self.should_reexport(name, obj_module_name, name_is_alias=False):
438 self.import_tracker.reexport(name)
439
440 self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})
441
442 if self.resort_members:
443 functions: list[str] = []
444 types: list[str] = []
445 variables: list[str] = []
446 else:
447 output: list[str] = []
448 functions = types = variables = output
449
450 for name, obj in items:
451 if self.is_function(obj):
452 self.generate_function_stub(name, obj, output=functions)
453 elif inspect.isclass(obj):
454 self.generate_class_stub(name, obj, output=types)
455 else:
456 self.generate_variable_stub(name, obj, output=variables)
457
458 self._output = []
459
460 if self.resort_members:
461 for line in variables:
462 self._output.append(line + "\n")
463 for line in types:
464 if line.startswith("class") and self._output and self._output[-1]:
465 self._output.append("\n")
466 self._output.append(line + "\n")
467 if self._output and functions:
468 self._output.append("\n")
469 for line in functions:
470 self._output.append(line + "\n")
471 else:
472 for i, line in enumerate(output):
473 if (
474 self._output
475 and line.startswith("class")
476 and (
477 not self._output[-1].startswith("class")
478 or (len(output) > i + 1 and output[i + 1].startswith(" "))
479 )
480 ) or (
481 self._output
482 and self._output[-1].startswith("def")
483 and not line.startswith("def")
484 ):
485 self._output.append("\n")
486 self._output.append(line + "\n")
487 self.check_undefined_names()
488
489 def is_skipped_attribute(self, attr: str) -> bool:
490 return (
491 attr
492 in (
493 "__class__",
494 "__getattribute__",
495 "__str__",
496 "__repr__",
497 "__doc__",
498 "__dict__",
499 "__module__",
500 "__weakref__",
501 "__annotations__",
502 "__firstlineno__",
503 "__static_attributes__",
504 "__annotate__",
505 )
506 or attr in self.IGNORED_DUNDERS
507 or is_pybind_skipped_attribute(attr) # For pickling
508 or keyword.iskeyword(attr)
509 )
510
511 def get_members(self, obj: object) -> list[tuple[str, Any]]:
512 obj_dict: Mapping[str, Any] = getattr(obj, "__dict__") # noqa: B009
513 results = []
514 for name in obj_dict:
515 if self.is_skipped_attribute(name):
516 continue
517 # Try to get the value via getattr
518 try:
519 value = getattr(obj, name)
520 except AttributeError:
521 continue
522 else:
523 results.append((name, value))
524 return results
525
526 def get_type_annotation(self, obj: object) -> str:
527 """
528 Given an instance, return a string representation of its type that is valid
529 to use as a type annotation.
530 """
531 if obj is None or obj is type(None):
532 return "None"
533 elif inspect.isclass(obj):
534 return f"type[{self.get_type_fullname(obj)}]"
535 elif isinstance(obj, FunctionType):
536 return self.add_name("typing.Callable")
537 elif isinstance(obj, ModuleType):
538 return self.add_name("types.ModuleType", require=False)
539 else:
540 return self.get_type_fullname(type(obj))
541
542 def is_function(self, obj: object) -> bool:
543 if self.is_c_module:
544 return inspect.isbuiltin(obj)
545 else:
546 return inspect.isfunction(obj)
547
548 def is_method(self, class_info: ClassInfo, name: str, obj: object) -> bool:
549 if self.is_c_module:
550 return inspect.ismethoddescriptor(obj) or type(obj) in (
551 type(str.index),
552 type(str.__add__),
553 type(str.__new__),
554 )
555 else:
556 # this is valid because it is only called on members of a class
557 return inspect.isfunction(obj)
558
559 def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool:
560 if self.is_c_module:
561 return inspect.isbuiltin(obj) or type(obj).__name__ in (
562 "classmethod",
563 "classmethod_descriptor",
564 )
565 else:
566 return inspect.ismethod(obj)
567
568 def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool:
569 if class_info is None:
570 return False
571 elif self.is_c_module:
572 raw_lookup: Mapping[str, Any] = getattr(class_info.cls, "__dict__") # noqa: B009
573 raw_value = raw_lookup.get(name, obj)
574 return isinstance(raw_value, staticmethod)
575 else:
576 return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod)
577
578 @staticmethod
579 def is_abstract_method(obj: object) -> bool:
580 return getattr(obj, "__abstractmethod__", False)
581
582 @staticmethod
583 def is_property(class_info: ClassInfo, name: str, obj: object) -> bool:
584 return inspect.isdatadescriptor(obj) or hasattr(obj, "fget")
585
586 @staticmethod
587 def is_property_readonly(prop: Any) -> bool:
588 return hasattr(prop, "fset") and prop.fset is None
589
590 def is_static_property(self, obj: object) -> bool:
591 """For c-modules, whether the property behaves like an attribute"""
592 if self.is_c_module:
593 # StaticProperty is from boost-python
594 return type(obj).__name__ in ("pybind11_static_property", "StaticProperty")
595 else:
596 return False
597
598 def process_inferred_sigs(self, inferred: list[FunctionSig]) -> None:
599 for i, sig in enumerate(inferred):
600 for arg in sig.args:
601 if arg.type is not None:
602 arg.type = self.strip_or_import(arg.type)
603 if sig.ret_type is not None:
604 inferred[i] = sig._replace(ret_type=self.strip_or_import(sig.ret_type))
605
606 def generate_function_stub(
607 self, name: str, obj: object, *, output: list[str], class_info: ClassInfo | None = None
608 ) -> None:
609 """Generate stub for a single function or method.
610
611 The result (always a single line) will be appended to 'output'.
612 If necessary, any required names will be added to 'imports'.
613 The 'class_name' is used to find signature of __init__ or __new__ in
614 'class_sigs'.
615 """
616 docstring: Any = getattr(obj, "__doc__", None)
617 if not isinstance(docstring, str):
618 docstring = None
619
620 ctx = FunctionContext(
621 self.module_name,
622 name,
623 docstring=docstring,
624 is_abstract=self.is_abstract_method(obj),
625 class_info=class_info,
626 )
627 if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):
628 return
629
630 self.record_name(ctx.name)
631 default_sig = self.get_default_function_sig(obj, ctx)
632 inferred = self.get_signatures(default_sig, self.sig_generators, ctx)
633 self.process_inferred_sigs(inferred)
634
635 decorators = []
636 if len(inferred) > 1:
637 decorators.append("@{}".format(self.add_name("typing.overload")))
638
639 if ctx.is_abstract:
640 decorators.append("@{}".format(self.add_name("abc.abstractmethod")))
641
642 if class_info is not None:
643 if self.is_staticmethod(class_info, name, obj):
644 decorators.append("@staticmethod")
645 else:
646 for sig in inferred:
647 if not sig.args or sig.args[0].name not in ("self", "cls"):
648 sig.args.insert(0, ArgSig(name=class_info.self_var))
649 # a sig generator indicates @classmethod by specifying the cls arg.
650 if inferred[0].args and inferred[0].args[0].name == "cls":
651 decorators.append("@classmethod")
652
653 docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None
654 output.extend(self.format_func_def(inferred, decorators=decorators, docstring=docstring))
655 self._fix_iter(ctx, inferred, output)
656
657 def _indent_docstring(self, docstring: str) -> str:
658 """Fix indentation of docstring extracted from pybind11 or other binding generators."""
659 lines = docstring.splitlines(keepends=True)
660 indent = self._indent + " "
661 if len(lines) > 1:
662 if not all(line.startswith(indent) or not line.strip() for line in lines):
663 # if the docstring is not indented, then indent all but the first line
664 for i, line in enumerate(lines[1:]):
665 if line.strip():
666 lines[i + 1] = indent + line
667 # if there's a trailing newline, add a final line to visually indent the quoted docstring
668 if lines[-1].endswith("\n"):
669 if len(lines) > 1:
670 lines.append(indent)
671 else:
672 lines[-1] = lines[-1][:-1]
673 return "".join(lines)
674
675 def _fix_iter(
676 self, ctx: FunctionContext, inferred: list[FunctionSig], output: list[str]
677 ) -> None:
678 """Ensure that objects which implement old-style iteration via __getitem__
679 are considered iterable.
680 """
681 if (
682 ctx.class_info
683 and ctx.class_info.cls is not None
684 and ctx.name == "__getitem__"
685 and "__iter__" not in ctx.class_info.cls.__dict__
686 ):
687 item_type: str | None = None
688 for sig in inferred:
689 if sig.args and sig.args[-1].type == "int":
690 item_type = sig.ret_type
691 break
692 if item_type is None:
693 return
694 obj = CFunctionStub(
695 "__iter__", f"def __iter__(self) -> typing.Iterator[{item_type}]\n"
696 )
697 self.generate_function_stub("__iter__", obj, output=output, class_info=ctx.class_info)
698
699 def generate_property_stub(
700 self,
701 name: str,
702 raw_obj: object,
703 obj: object,
704 static_properties: list[str],
705 rw_properties: list[str],
706 ro_properties: list[str],
707 class_info: ClassInfo | None = None,
708 ) -> None:
709 """Generate property stub using introspection of 'obj'.
710
711 Try to infer type from docstring, append resulting lines to 'output'.
712
713 raw_obj : object before evaluation of descriptor (if any)
714 obj : object after evaluation of descriptor
715 """
716
717 docstring = getattr(raw_obj, "__doc__", None)
718 fget = getattr(raw_obj, "fget", None)
719 if fget:
720 alt_docstr = getattr(fget, "__doc__", None)
721 if alt_docstr and docstring:
722 docstring += "\n" + alt_docstr
723 elif alt_docstr:
724 docstring = alt_docstr
725
726 ctx = FunctionContext(
727 self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info
728 )
729
730 if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):
731 return
732
733 self.record_name(ctx.name)
734 static = self.is_static_property(raw_obj)
735 readonly = self.is_property_readonly(raw_obj)
736 if static:
737 ret_type: str | None = self.strip_or_import(self.get_type_annotation(obj))
738 else:
739 default_sig = self.get_default_function_sig(raw_obj, ctx)
740 ret_type = default_sig.ret_type
741
742 inferred_type = self.get_property_type(ret_type, self.sig_generators, ctx)
743 if inferred_type is not None:
744 inferred_type = self.strip_or_import(inferred_type)
745
746 if static:
747 classvar = self.add_name("typing.ClassVar")
748 trailing_comment = " # read-only" if readonly else ""
749 if inferred_type is None:
750 inferred_type = self.add_name("_typeshed.Incomplete")
751
752 static_properties.append(
753 f"{self._indent}{name}: {classvar}[{inferred_type}] = ...{trailing_comment}"
754 )
755 else: # regular property
756 if readonly:
757 docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None
758 ro_properties.append(f"{self._indent}@property")
759 sig = FunctionSig(name, [ArgSig("self")], inferred_type, docstring=docstring)
760 ro_properties.append(
761 sig.format_sig(
762 indent=self._indent, include_docstrings=self._include_docstrings
763 )
764 )
765 else:
766 if inferred_type is None:
767 inferred_type = self.add_name("_typeshed.Incomplete")
768
769 rw_properties.append(f"{self._indent}{name}: {inferred_type}")
770
771 def get_type_fullname(self, typ: type) -> str:
772 """Given a type, return a string representation"""
773 if typ is Any:
774 return "Any"
775 typename = getattr(typ, "__qualname__", typ.__name__)
776 module_name = self.get_obj_module(typ)
777 if module_name is None:
778 # This should not normally happen, but some types may resist our
779 # introspection attempts too hard. See
780 # https://github.com/python/mypy/issues/19031
781 return "_typeshed.Incomplete"
782 if module_name != "builtins":
783 typename = f"{module_name}.{typename}"
784 return typename
785
786 def get_base_types(self, obj: type) -> list[str]:
787 all_bases = type.mro(obj)
788 if all_bases[-1] is object:
789 # TODO: Is this always object?
790 del all_bases[-1]
791 # remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO,
792 # which only overrides a few functions in object type
793 if all_bases and all_bases[-1].__name__ == "pybind11_object":
794 del all_bases[-1]
795 # remove the class itself
796 all_bases = all_bases[1:]
797 # Remove base classes of other bases as redundant.
798 bases: list[type] = []
799 for base in all_bases:
800 if not any(issubclass(b, base) for b in bases):
801 bases.append(base)
802 return [self.strip_or_import(self.get_type_fullname(base)) for base in bases]
803
804 def generate_class_stub(
805 self, class_name: str, cls: type, output: list[str], parent_class: ClassInfo | None = None
806 ) -> None:
807 """Generate stub for a single class using runtime introspection.
808
809 The result lines will be appended to 'output'. If necessary, any
810 required names will be added to 'imports'.
811 """
812 raw_lookup: Mapping[str, Any] = getattr(cls, "__dict__") # noqa: B009
813 items = self.get_members(cls)
814 if self.resort_members:
815 items = sorted(items, key=lambda x: method_name_sort_key(x[0]))
816 names = {x[0] for x in items}
817 methods: list[str] = []
818 types: list[str] = []
819 static_properties: list[str] = []
820 rw_properties: list[str] = []
821 ro_properties: list[str] = []
822 attrs: list[tuple[str, Any]] = []
823
824 self.record_name(class_name)
825 self.indent()
826
827 class_info = ClassInfo(
828 class_name, "", getattr(cls, "__doc__", None), cls, parent=parent_class
829 )
830
831 for attr, value in items:
832 # use unevaluated descriptors when dealing with property inspection
833 raw_value = raw_lookup.get(attr, value)
834 if self.is_method(class_info, attr, value) or self.is_classmethod(
835 class_info, attr, value
836 ):
837 if attr == "__new__":
838 # TODO: We should support __new__.
839 if "__init__" in names:
840 # Avoid duplicate functions if both are present.
841 # But is there any case where .__new__() has a
842 # better signature than __init__() ?
843 continue
844 attr = "__init__"
845 # FIXME: make this nicer
846 if self.is_staticmethod(class_info, attr, value):
847 class_info.self_var = ""
848 elif self.is_classmethod(class_info, attr, value):
849 class_info.self_var = "cls"
850 else:
851 class_info.self_var = "self"
852 self.generate_function_stub(attr, value, output=methods, class_info=class_info)
853 elif self.is_property(class_info, attr, raw_value):
854 self.generate_property_stub(
855 attr,
856 raw_value,
857 value,
858 static_properties,
859 rw_properties,
860 ro_properties,
861 class_info,
862 )
863 elif inspect.isclass(value) and self.is_defined_in_module(value):
864 self.generate_class_stub(attr, value, types, parent_class=class_info)
865 else:
866 attrs.append((attr, value))
867
868 for attr, value in attrs:
869 if attr == "__hash__" and value is None:
870 # special case for __hash__
871 continue
872 prop_type_name = self.strip_or_import(self.get_type_annotation(value))
873 classvar = self.add_name("typing.ClassVar")
874 static_properties.append(f"{self._indent}{attr}: {classvar}[{prop_type_name}] = ...")
875
876 self.dedent()
877
878 bases = self.get_base_types(cls)
879 if bases:
880 bases_str = "(%s)" % ", ".join(bases)
881 else:
882 bases_str = ""
883
884 if class_info.docstring and self._include_docstrings:
885 doc = quote_docstring(self._indent_docstring(class_info.docstring))
886 doc = f" {self._indent}{doc}"
887 docstring = doc.splitlines(keepends=False)
888 else:
889 docstring = []
890
891 if docstring or types or static_properties or rw_properties or methods or ro_properties:
892 output.append(f"{self._indent}class {class_name}{bases_str}:")
893 output.extend(docstring)
894 for line in types:
895 if (
896 output
897 and output[-1]
898 and not output[-1].strip().startswith("class")
899 and line.strip().startswith("class")
900 ):
901 output.append("")
902 output.append(line)
903 output.extend(static_properties)
904 output.extend(rw_properties)
905 output.extend(methods)
906 output.extend(ro_properties)
907 else:
908 output.append(f"{self._indent}class {class_name}{bases_str}: ...")
909
910 def generate_variable_stub(self, name: str, obj: object, output: list[str]) -> None:
911 """Generate stub for a single variable using runtime introspection.
912
913 The result lines will be appended to 'output'. If necessary, any
914 required names will be added to 'imports'.
915 """
916 if self.is_private_name(name, f"{self.module_name}.{name}") or self.is_not_in_all(name):
917 return
918 self.record_name(name)
919 type_str = self.strip_or_import(self.get_type_annotation(obj))
920 output.append(f"{name}: {type_str}")
921
922
923 def method_name_sort_key(name: str) -> tuple[int, str]:
924 """Sort methods in classes in a typical order.
925
926 I.e.: constructor, normal methods, special methods.
927 """
928 if name in ("__new__", "__init__"):
929 return 0, name
930 if name.startswith("__") and name.endswith("__"):
931 return 2, name
932 return 1, name
933
934
935 def is_pybind_skipped_attribute(attr: str) -> bool:
936 return attr.startswith("__pybind11_module_local_")
937
938
939 def infer_c_method_args(
940 name: str, self_var: str = "self", arg_names: list[str] | None = None
941 ) -> list[ArgSig]:
942 args: list[ArgSig] | None = None
943 if name.startswith("__") and name.endswith("__"):
944 name = name[2:-2]
945 if name in (
946 "hash",
947 "iter",
948 "next",
949 "sizeof",
950 "copy",
951 "deepcopy",
952 "reduce",
953 "getinitargs",
954 "int",
955 "float",
956 "trunc",
957 "complex",
958 "bool",
959 "abs",
960 "bytes",
961 "dir",
962 "len",
963 "reversed",
964 "round",
965 "index",
966 "enter",
967 ):
968 args = []
969 elif name == "getitem":
970 args = [ArgSig(name="index")]
971 elif name == "setitem":
972 args = [ArgSig(name="index"), ArgSig(name="object")]
973 elif name in ("delattr", "getattr"):
974 args = [ArgSig(name="name")]
975 elif name == "setattr":
976 args = [ArgSig(name="name"), ArgSig(name="value")]
977 elif name == "getstate":
978 args = []
979 elif name == "setstate":
980 args = [ArgSig(name="state")]
981 elif name in ("eq", "ne", "lt", "le", "gt", "ge"):
982 args = [ArgSig(name="other", type="object")]
983 elif name in (
984 "add",
985 "radd",
986 "sub",
987 "rsub",
988 "mul",
989 "rmul",
990 "mod",
991 "rmod",
992 "floordiv",
993 "rfloordiv",
994 "truediv",
995 "rtruediv",
996 "divmod",
997 "rdivmod",
998 "pow",
999 "rpow",
1000 "xor",
1001 "rxor",
1002 "or",
1003 "ror",
1004 "and",
1005 "rand",
1006 "lshift",
1007 "rlshift",
1008 "rshift",
1009 "rrshift",
1010 "contains",
1011 "delitem",
1012 "iadd",
1013 "iand",
1014 "ifloordiv",
1015 "ilshift",
1016 "imod",
1017 "imul",
1018 "ior",
1019 "ipow",
1020 "irshift",
1021 "isub",
1022 "itruediv",
1023 "ixor",
1024 ):
1025 args = [ArgSig(name="other")]
1026 elif name in ("neg", "pos", "invert"):
1027 args = []
1028 elif name == "get":
1029 args = [ArgSig(name="instance"), ArgSig(name="owner")]
1030 elif name == "set":
1031 args = [ArgSig(name="instance"), ArgSig(name="value")]
1032 elif name == "reduce_ex":
1033 args = [ArgSig(name="protocol")]
1034 elif name == "exit":
1035 args = [
1036 ArgSig(name="type", type="type[BaseException] | None"),
1037 ArgSig(name="value", type="BaseException | None"),
1038 ArgSig(name="traceback", type="types.TracebackType | None"),
1039 ]
1040 if args is None:
1041 args = infer_method_arg_types(name, self_var, arg_names)
1042 else:
1043 args = [ArgSig(name=self_var)] + args
1044 if args is None:
1045 args = [ArgSig(name="*args"), ArgSig(name="**kwargs")]
1046 return args