stubgenc.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. #!/usr/bin/env python3
  2. """Stub generator for C modules.
  3. The public interface is via the mypy.stubgen module.
  4. """
  5. from __future__ import annotations
  6. import importlib
  7. import inspect
  8. import os.path
  9. import re
  10. from abc import abstractmethod
  11. from types import ModuleType
  12. from typing import Any, Iterable, Mapping
  13. from typing_extensions import Final
  14. from mypy.moduleinspect import is_c_module
  15. from mypy.stubdoc import (
  16. ArgSig,
  17. FunctionSig,
  18. infer_arg_sig_from_anon_docstring,
  19. infer_prop_type_from_docstring,
  20. infer_ret_type_sig_from_anon_docstring,
  21. infer_ret_type_sig_from_docstring,
  22. infer_sig_from_docstring,
  23. )
  24. # Members of the typing module to consider for importing by default.
  25. _DEFAULT_TYPING_IMPORTS: Final = (
  26. "Any",
  27. "Callable",
  28. "ClassVar",
  29. "Dict",
  30. "Iterable",
  31. "Iterator",
  32. "List",
  33. "Optional",
  34. "Tuple",
  35. "Union",
  36. )
  37. class SignatureGenerator:
  38. """Abstract base class for extracting a list of FunctionSigs for each function."""
  39. def remove_self_type(
  40. self, inferred: list[FunctionSig] | None, self_var: str
  41. ) -> list[FunctionSig] | None:
  42. """Remove type annotation from self/cls argument"""
  43. if inferred:
  44. for signature in inferred:
  45. if signature.args:
  46. if signature.args[0].name == self_var:
  47. signature.args[0].type = None
  48. return inferred
  49. @abstractmethod
  50. def get_function_sig(
  51. self, func: object, module_name: str, name: str
  52. ) -> list[FunctionSig] | None:
  53. pass
  54. @abstractmethod
  55. def get_method_sig(
  56. self, cls: type, func: object, module_name: str, class_name: str, name: str, self_var: str
  57. ) -> list[FunctionSig] | None:
  58. pass
  59. class ExternalSignatureGenerator(SignatureGenerator):
  60. def __init__(
  61. self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None
  62. ):
  63. """
  64. Takes a mapping of function/method names to signatures and class name to
  65. class signatures (usually corresponds to __init__).
  66. """
  67. self.func_sigs = func_sigs or {}
  68. self.class_sigs = class_sigs or {}
  69. def get_function_sig(
  70. self, func: object, module_name: str, name: str
  71. ) -> list[FunctionSig] | None:
  72. if name in self.func_sigs:
  73. return [
  74. FunctionSig(
  75. name=name,
  76. args=infer_arg_sig_from_anon_docstring(self.func_sigs[name]),
  77. ret_type="Any",
  78. )
  79. ]
  80. else:
  81. return None
  82. def get_method_sig(
  83. self, cls: type, func: object, module_name: str, class_name: str, name: str, self_var: str
  84. ) -> list[FunctionSig] | None:
  85. if (
  86. name in ("__new__", "__init__")
  87. and name not in self.func_sigs
  88. and class_name in self.class_sigs
  89. ):
  90. return [
  91. FunctionSig(
  92. name=name,
  93. args=infer_arg_sig_from_anon_docstring(self.class_sigs[class_name]),
  94. ret_type=infer_method_ret_type(name),
  95. )
  96. ]
  97. inferred = self.get_function_sig(func, module_name, name)
  98. return self.remove_self_type(inferred, self_var)
  99. class DocstringSignatureGenerator(SignatureGenerator):
  100. def get_function_sig(
  101. self, func: object, module_name: str, name: str
  102. ) -> list[FunctionSig] | None:
  103. docstr = getattr(func, "__doc__", None)
  104. inferred = infer_sig_from_docstring(docstr, name)
  105. if inferred:
  106. assert docstr is not None
  107. if is_pybind11_overloaded_function_docstring(docstr, name):
  108. # Remove pybind11 umbrella (*args, **kwargs) for overloaded functions
  109. del inferred[-1]
  110. return inferred
  111. def get_method_sig(
  112. self,
  113. cls: type,
  114. func: object,
  115. module_name: str,
  116. class_name: str,
  117. func_name: str,
  118. self_var: str,
  119. ) -> list[FunctionSig] | None:
  120. inferred = self.get_function_sig(func, module_name, func_name)
  121. if not inferred and func_name == "__init__":
  122. # look for class-level constructor signatures of the form <class_name>(<signature>)
  123. inferred = self.get_function_sig(cls, module_name, class_name)
  124. return self.remove_self_type(inferred, self_var)
  125. class FallbackSignatureGenerator(SignatureGenerator):
  126. def get_function_sig(
  127. self, func: object, module_name: str, name: str
  128. ) -> list[FunctionSig] | None:
  129. return [
  130. FunctionSig(
  131. name=name,
  132. args=infer_arg_sig_from_anon_docstring("(*args, **kwargs)"),
  133. ret_type="Any",
  134. )
  135. ]
  136. def get_method_sig(
  137. self, cls: type, func: object, module_name: str, class_name: str, name: str, self_var: str
  138. ) -> list[FunctionSig] | None:
  139. return [
  140. FunctionSig(
  141. name=name,
  142. args=infer_method_args(name, self_var),
  143. ret_type=infer_method_ret_type(name),
  144. )
  145. ]
  146. def generate_stub_for_c_module(
  147. module_name: str,
  148. target: str,
  149. known_modules: list[str],
  150. sig_generators: Iterable[SignatureGenerator],
  151. ) -> None:
  152. """Generate stub for C module.
  153. Signature generators are called in order until a list of signatures is returned. The order
  154. is:
  155. - signatures inferred from .rst documentation (if given)
  156. - simple runtime introspection (looking for docstrings and attributes
  157. with simple builtin types)
  158. - fallback based special method names or "(*args, **kwargs)"
  159. If directory for target doesn't exist it will be created. Existing stub
  160. will be overwritten.
  161. """
  162. module = importlib.import_module(module_name)
  163. assert is_c_module(module), f"{module_name} is not a C module"
  164. subdir = os.path.dirname(target)
  165. if subdir and not os.path.isdir(subdir):
  166. os.makedirs(subdir)
  167. imports: list[str] = []
  168. functions: list[str] = []
  169. done = set()
  170. items = sorted(get_members(module), key=lambda x: x[0])
  171. for name, obj in items:
  172. if is_c_function(obj):
  173. generate_c_function_stub(
  174. module,
  175. name,
  176. obj,
  177. output=functions,
  178. known_modules=known_modules,
  179. imports=imports,
  180. sig_generators=sig_generators,
  181. )
  182. done.add(name)
  183. types: list[str] = []
  184. for name, obj in items:
  185. if name.startswith("__") and name.endswith("__"):
  186. continue
  187. if is_c_type(obj):
  188. generate_c_type_stub(
  189. module,
  190. name,
  191. obj,
  192. output=types,
  193. known_modules=known_modules,
  194. imports=imports,
  195. sig_generators=sig_generators,
  196. )
  197. done.add(name)
  198. variables = []
  199. for name, obj in items:
  200. if name.startswith("__") and name.endswith("__"):
  201. continue
  202. if name not in done and not inspect.ismodule(obj):
  203. type_str = strip_or_import(
  204. get_type_fullname(type(obj)), module, known_modules, imports
  205. )
  206. variables.append(f"{name}: {type_str}")
  207. output = sorted(set(imports))
  208. for line in variables:
  209. output.append(line)
  210. for line in types:
  211. if line.startswith("class") and output and output[-1]:
  212. output.append("")
  213. output.append(line)
  214. if output and functions:
  215. output.append("")
  216. for line in functions:
  217. output.append(line)
  218. output = add_typing_import(output)
  219. with open(target, "w") as file:
  220. for line in output:
  221. file.write(f"{line}\n")
  222. def add_typing_import(output: list[str]) -> list[str]:
  223. """Add typing imports for collections/types that occur in the generated stub."""
  224. names = []
  225. for name in _DEFAULT_TYPING_IMPORTS:
  226. if any(re.search(r"\b%s\b" % name, line) for line in output):
  227. names.append(name)
  228. if names:
  229. return [f"from typing import {', '.join(names)}", ""] + output
  230. else:
  231. return output.copy()
  232. def get_members(obj: object) -> list[tuple[str, Any]]:
  233. obj_dict: Mapping[str, Any] = getattr(obj, "__dict__") # noqa: B009
  234. results = []
  235. for name in obj_dict:
  236. if is_skipped_attribute(name):
  237. continue
  238. # Try to get the value via getattr
  239. try:
  240. value = getattr(obj, name)
  241. except AttributeError:
  242. continue
  243. else:
  244. results.append((name, value))
  245. return results
  246. def is_c_function(obj: object) -> bool:
  247. return inspect.isbuiltin(obj) or type(obj) is type(ord)
  248. def is_c_method(obj: object) -> bool:
  249. return inspect.ismethoddescriptor(obj) or type(obj) in (
  250. type(str.index),
  251. type(str.__add__),
  252. type(str.__new__),
  253. )
  254. def is_c_classmethod(obj: object) -> bool:
  255. return inspect.isbuiltin(obj) or type(obj).__name__ in (
  256. "classmethod",
  257. "classmethod_descriptor",
  258. )
  259. def is_c_property(obj: object) -> bool:
  260. return inspect.isdatadescriptor(obj) or hasattr(obj, "fget")
  261. def is_c_property_readonly(prop: Any) -> bool:
  262. return hasattr(prop, "fset") and prop.fset is None
  263. def is_c_type(obj: object) -> bool:
  264. return inspect.isclass(obj) or type(obj) is type(int)
  265. def is_pybind11_overloaded_function_docstring(docstr: str, name: str) -> bool:
  266. return docstr.startswith(f"{name}(*args, **kwargs)\n" + "Overloaded function.\n\n")
  267. def generate_c_function_stub(
  268. module: ModuleType,
  269. name: str,
  270. obj: object,
  271. *,
  272. known_modules: list[str],
  273. sig_generators: Iterable[SignatureGenerator],
  274. output: list[str],
  275. imports: list[str],
  276. self_var: str | None = None,
  277. cls: type | None = None,
  278. class_name: str | None = None,
  279. ) -> None:
  280. """Generate stub for a single function or method.
  281. The result (always a single line) will be appended to 'output'.
  282. If necessary, any required names will be added to 'imports'.
  283. The 'class_name' is used to find signature of __init__ or __new__ in
  284. 'class_sigs'.
  285. """
  286. inferred: list[FunctionSig] | None = None
  287. if class_name:
  288. # method:
  289. assert cls is not None, "cls should be provided for methods"
  290. assert self_var is not None, "self_var should be provided for methods"
  291. for sig_gen in sig_generators:
  292. inferred = sig_gen.get_method_sig(
  293. cls, obj, module.__name__, class_name, name, self_var
  294. )
  295. if inferred:
  296. # add self/cls var, if not present
  297. for sig in inferred:
  298. if not sig.args or sig.args[0].name not in ("self", "cls"):
  299. sig.args.insert(0, ArgSig(name=self_var))
  300. break
  301. else:
  302. # function:
  303. for sig_gen in sig_generators:
  304. inferred = sig_gen.get_function_sig(obj, module.__name__, name)
  305. if inferred:
  306. break
  307. if not inferred:
  308. raise ValueError(
  309. "No signature was found. This should never happen "
  310. "if FallbackSignatureGenerator is provided"
  311. )
  312. is_overloaded = len(inferred) > 1 if inferred else False
  313. if is_overloaded:
  314. imports.append("from typing import overload")
  315. if inferred:
  316. for signature in inferred:
  317. args: list[str] = []
  318. for arg in signature.args:
  319. arg_def = arg.name
  320. if arg_def == "None":
  321. arg_def = "_none" # None is not a valid argument name
  322. if arg.type:
  323. arg_def += ": " + strip_or_import(arg.type, module, known_modules, imports)
  324. if arg.default:
  325. arg_def += " = ..."
  326. args.append(arg_def)
  327. if is_overloaded:
  328. output.append("@overload")
  329. # a sig generator indicates @classmethod by specifying the cls arg
  330. if class_name and signature.args and signature.args[0].name == "cls":
  331. output.append("@classmethod")
  332. output.append(
  333. "def {function}({args}) -> {ret}: ...".format(
  334. function=name,
  335. args=", ".join(args),
  336. ret=strip_or_import(signature.ret_type, module, known_modules, imports),
  337. )
  338. )
  339. def strip_or_import(
  340. typ: str, module: ModuleType, known_modules: list[str], imports: list[str]
  341. ) -> str:
  342. """Strips unnecessary module names from typ.
  343. If typ represents a type that is inside module or is a type coming from builtins, remove
  344. module declaration from it. Return stripped name of the type.
  345. Arguments:
  346. typ: name of the type
  347. module: in which this type is used
  348. known_modules: other modules being processed
  349. imports: list of import statements (may be modified during the call)
  350. """
  351. local_modules = ["builtins"]
  352. if module:
  353. local_modules.append(module.__name__)
  354. stripped_type = typ
  355. if any(c in typ for c in "[,"):
  356. for subtyp in re.split(r"[\[,\]]", typ):
  357. stripped_subtyp = strip_or_import(subtyp.strip(), module, known_modules, imports)
  358. if stripped_subtyp != subtyp:
  359. stripped_type = re.sub(
  360. r"(^|[\[, ]+)" + re.escape(subtyp) + r"($|[\], ]+)",
  361. r"\1" + stripped_subtyp + r"\2",
  362. stripped_type,
  363. )
  364. elif "." in typ:
  365. for module_name in local_modules + list(reversed(known_modules)):
  366. if typ.startswith(module_name + "."):
  367. if module_name in local_modules:
  368. stripped_type = typ[len(module_name) + 1 :]
  369. arg_module = module_name
  370. break
  371. else:
  372. arg_module = typ[: typ.rindex(".")]
  373. if arg_module not in local_modules:
  374. imports.append(f"import {arg_module}")
  375. if stripped_type == "NoneType":
  376. stripped_type = "None"
  377. return stripped_type
  378. def is_static_property(obj: object) -> bool:
  379. return type(obj).__name__ == "pybind11_static_property"
  380. def generate_c_property_stub(
  381. name: str,
  382. obj: object,
  383. static_properties: list[str],
  384. rw_properties: list[str],
  385. ro_properties: list[str],
  386. readonly: bool,
  387. module: ModuleType | None = None,
  388. known_modules: list[str] | None = None,
  389. imports: list[str] | None = None,
  390. ) -> None:
  391. """Generate property stub using introspection of 'obj'.
  392. Try to infer type from docstring, append resulting lines to 'output'.
  393. """
  394. def infer_prop_type(docstr: str | None) -> str | None:
  395. """Infer property type from docstring or docstring signature."""
  396. if docstr is not None:
  397. inferred = infer_ret_type_sig_from_anon_docstring(docstr)
  398. if not inferred:
  399. inferred = infer_ret_type_sig_from_docstring(docstr, name)
  400. if not inferred:
  401. inferred = infer_prop_type_from_docstring(docstr)
  402. return inferred
  403. else:
  404. return None
  405. inferred = infer_prop_type(getattr(obj, "__doc__", None))
  406. if not inferred:
  407. fget = getattr(obj, "fget", None)
  408. inferred = infer_prop_type(getattr(fget, "__doc__", None))
  409. if not inferred:
  410. inferred = "Any"
  411. if module is not None and imports is not None and known_modules is not None:
  412. inferred = strip_or_import(inferred, module, known_modules, imports)
  413. if is_static_property(obj):
  414. trailing_comment = " # read-only" if readonly else ""
  415. static_properties.append(f"{name}: ClassVar[{inferred}] = ...{trailing_comment}")
  416. else: # regular property
  417. if readonly:
  418. ro_properties.append("@property")
  419. ro_properties.append(f"def {name}(self) -> {inferred}: ...")
  420. else:
  421. rw_properties.append(f"{name}: {inferred}")
  422. def generate_c_type_stub(
  423. module: ModuleType,
  424. class_name: str,
  425. obj: type,
  426. output: list[str],
  427. known_modules: list[str],
  428. imports: list[str],
  429. sig_generators: Iterable[SignatureGenerator],
  430. ) -> None:
  431. """Generate stub for a single class using runtime introspection.
  432. The result lines will be appended to 'output'. If necessary, any
  433. required names will be added to 'imports'.
  434. """
  435. raw_lookup = getattr(obj, "__dict__") # noqa: B009
  436. items = sorted(get_members(obj), key=lambda x: method_name_sort_key(x[0]))
  437. names = set(x[0] for x in items)
  438. methods: list[str] = []
  439. types: list[str] = []
  440. static_properties: list[str] = []
  441. rw_properties: list[str] = []
  442. ro_properties: list[str] = []
  443. attrs: list[tuple[str, Any]] = []
  444. for attr, value in items:
  445. # use unevaluated descriptors when dealing with property inspection
  446. raw_value = raw_lookup.get(attr, value)
  447. if is_c_method(value) or is_c_classmethod(value):
  448. if attr == "__new__":
  449. # TODO: We should support __new__.
  450. if "__init__" in names:
  451. # Avoid duplicate functions if both are present.
  452. # But is there any case where .__new__() has a
  453. # better signature than __init__() ?
  454. continue
  455. attr = "__init__"
  456. if is_c_classmethod(value):
  457. self_var = "cls"
  458. else:
  459. self_var = "self"
  460. generate_c_function_stub(
  461. module,
  462. attr,
  463. value,
  464. output=methods,
  465. known_modules=known_modules,
  466. imports=imports,
  467. self_var=self_var,
  468. cls=obj,
  469. class_name=class_name,
  470. sig_generators=sig_generators,
  471. )
  472. elif is_c_property(raw_value):
  473. generate_c_property_stub(
  474. attr,
  475. raw_value,
  476. static_properties,
  477. rw_properties,
  478. ro_properties,
  479. is_c_property_readonly(raw_value),
  480. module=module,
  481. known_modules=known_modules,
  482. imports=imports,
  483. )
  484. elif is_c_type(value):
  485. generate_c_type_stub(
  486. module,
  487. attr,
  488. value,
  489. types,
  490. imports=imports,
  491. known_modules=known_modules,
  492. sig_generators=sig_generators,
  493. )
  494. else:
  495. attrs.append((attr, value))
  496. for attr, value in attrs:
  497. static_properties.append(
  498. "{}: ClassVar[{}] = ...".format(
  499. attr,
  500. strip_or_import(get_type_fullname(type(value)), module, known_modules, imports),
  501. )
  502. )
  503. all_bases = type.mro(obj)
  504. if all_bases[-1] is object:
  505. # TODO: Is this always object?
  506. del all_bases[-1]
  507. # remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO,
  508. # which only overrides a few functions in object type
  509. if all_bases and all_bases[-1].__name__ == "pybind11_object":
  510. del all_bases[-1]
  511. # remove the class itself
  512. all_bases = all_bases[1:]
  513. # Remove base classes of other bases as redundant.
  514. bases: list[type] = []
  515. for base in all_bases:
  516. if not any(issubclass(b, base) for b in bases):
  517. bases.append(base)
  518. if bases:
  519. bases_str = "(%s)" % ", ".join(
  520. strip_or_import(get_type_fullname(base), module, known_modules, imports)
  521. for base in bases
  522. )
  523. else:
  524. bases_str = ""
  525. if types or static_properties or rw_properties or methods or ro_properties:
  526. output.append(f"class {class_name}{bases_str}:")
  527. for line in types:
  528. if (
  529. output
  530. and output[-1]
  531. and not output[-1].startswith("class")
  532. and line.startswith("class")
  533. ):
  534. output.append("")
  535. output.append(" " + line)
  536. for line in static_properties:
  537. output.append(f" {line}")
  538. for line in rw_properties:
  539. output.append(f" {line}")
  540. for line in methods:
  541. output.append(f" {line}")
  542. for line in ro_properties:
  543. output.append(f" {line}")
  544. else:
  545. output.append(f"class {class_name}{bases_str}: ...")
  546. def get_type_fullname(typ: type) -> str:
  547. return f"{typ.__module__}.{getattr(typ, '__qualname__', typ.__name__)}"
  548. def method_name_sort_key(name: str) -> tuple[int, str]:
  549. """Sort methods in classes in a typical order.
  550. I.e.: constructor, normal methods, special methods.
  551. """
  552. if name in ("__new__", "__init__"):
  553. return 0, name
  554. if name.startswith("__") and name.endswith("__"):
  555. return 2, name
  556. return 1, name
  557. def is_pybind_skipped_attribute(attr: str) -> bool:
  558. return attr.startswith("__pybind11_module_local_")
  559. def is_skipped_attribute(attr: str) -> bool:
  560. return attr in (
  561. "__class__",
  562. "__getattribute__",
  563. "__str__",
  564. "__repr__",
  565. "__doc__",
  566. "__dict__",
  567. "__module__",
  568. "__weakref__",
  569. ) or is_pybind_skipped_attribute( # For pickling
  570. attr
  571. )
  572. def infer_method_args(name: str, self_var: str | None = None) -> list[ArgSig]:
  573. args: list[ArgSig] | None = None
  574. if name.startswith("__") and name.endswith("__"):
  575. name = name[2:-2]
  576. if name in (
  577. "hash",
  578. "iter",
  579. "next",
  580. "sizeof",
  581. "copy",
  582. "deepcopy",
  583. "reduce",
  584. "getinitargs",
  585. "int",
  586. "float",
  587. "trunc",
  588. "complex",
  589. "bool",
  590. "abs",
  591. "bytes",
  592. "dir",
  593. "len",
  594. "reversed",
  595. "round",
  596. "index",
  597. "enter",
  598. ):
  599. args = []
  600. elif name == "getitem":
  601. args = [ArgSig(name="index")]
  602. elif name == "setitem":
  603. args = [ArgSig(name="index"), ArgSig(name="object")]
  604. elif name in ("delattr", "getattr"):
  605. args = [ArgSig(name="name")]
  606. elif name == "setattr":
  607. args = [ArgSig(name="name"), ArgSig(name="value")]
  608. elif name == "getstate":
  609. args = []
  610. elif name == "setstate":
  611. args = [ArgSig(name="state")]
  612. elif name in (
  613. "eq",
  614. "ne",
  615. "lt",
  616. "le",
  617. "gt",
  618. "ge",
  619. "add",
  620. "radd",
  621. "sub",
  622. "rsub",
  623. "mul",
  624. "rmul",
  625. "mod",
  626. "rmod",
  627. "floordiv",
  628. "rfloordiv",
  629. "truediv",
  630. "rtruediv",
  631. "divmod",
  632. "rdivmod",
  633. "pow",
  634. "rpow",
  635. "xor",
  636. "rxor",
  637. "or",
  638. "ror",
  639. "and",
  640. "rand",
  641. "lshift",
  642. "rlshift",
  643. "rshift",
  644. "rrshift",
  645. "contains",
  646. "delitem",
  647. "iadd",
  648. "iand",
  649. "ifloordiv",
  650. "ilshift",
  651. "imod",
  652. "imul",
  653. "ior",
  654. "ipow",
  655. "irshift",
  656. "isub",
  657. "itruediv",
  658. "ixor",
  659. ):
  660. args = [ArgSig(name="other")]
  661. elif name in ("neg", "pos", "invert"):
  662. args = []
  663. elif name == "get":
  664. args = [ArgSig(name="instance"), ArgSig(name="owner")]
  665. elif name == "set":
  666. args = [ArgSig(name="instance"), ArgSig(name="value")]
  667. elif name == "reduce_ex":
  668. args = [ArgSig(name="protocol")]
  669. elif name == "exit":
  670. args = [ArgSig(name="type"), ArgSig(name="value"), ArgSig(name="traceback")]
  671. if args is None:
  672. args = [ArgSig(name="*args"), ArgSig(name="**kwargs")]
  673. return [ArgSig(name=self_var or "self")] + args
  674. def infer_method_ret_type(name: str) -> str:
  675. if name.startswith("__") and name.endswith("__"):
  676. name = name[2:-2]
  677. if name in ("float", "bool", "bytes", "int"):
  678. return name
  679. # Note: __eq__ and co may return arbitrary types, but bool is good enough for stubgen.
  680. elif name in ("eq", "ne", "lt", "le", "gt", "ge", "contains"):
  681. return "bool"
  682. elif name in ("len", "hash", "sizeof", "trunc", "floor", "ceil"):
  683. return "int"
  684. elif name in ("init", "setitem"):
  685. return "None"
  686. return "Any"