stubgenc.py 24 KB

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