forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstubgen.py
executable file
·1859 lines (1631 loc) · 67.2 KB
/
stubgen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Generator of dynamically typed draft stubs for arbitrary modules.
The logic of this script can be split in three steps:
* parsing options and finding sources:
- use runtime imports be default (to find also C modules)
- or use mypy's mechanisms, if importing is prohibited
* (optionally) semantically analysing the sources using mypy (as a single set)
* emitting the stubs text:
- for Python modules: from ASTs using StubGenerator
- for C modules using runtime introspection and (optionally) Sphinx docs
During first and third steps some problematic files can be skipped, but any
blocking error during second step will cause the whole program to stop.
Basic usage:
$ stubgen foo.py bar.py some_directory
=> Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively).
$ stubgen -m urllib.parse
=> Generate out/urllib/parse.pyi.
$ stubgen -p urllib
=> Generate stubs for whole urlib package (recursively).
For C modules, you can get more precise function signatures by parsing .rst (Sphinx)
documentation for extra information. For this, use the --doc-dir option:
$ stubgen --doc-dir <DIR>/Python-3.4.2/Doc/library -m curses
Note: The generated stubs should be verified manually.
TODO:
- maybe use .rst docs also for Python modules
- maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example)
- a quick and dirty heuristic would be to turn this on if a module has something like
'from x import y as _y'
- we don't seem to always detect properties ('closed' in 'io', for example)
"""
from __future__ import annotations
import argparse
import glob
import os
import os.path
import sys
import traceback
from collections import defaultdict
from typing import Iterable, List, Mapping, cast
from typing_extensions import Final
import mypy.build
import mypy.mixedtraverser
import mypy.parse
import mypy.traverser
import mypy.util
from mypy.build import build
from mypy.errors import CompileError, Errors
from mypy.find_sources import InvalidSourceList, create_source_list
from mypy.modulefinder import (
BuildSource,
FindModuleCache,
ModuleNotFoundReason,
SearchPaths,
default_lib_path,
)
from mypy.moduleinspect import ModuleInspect
from mypy.nodes import (
ARG_NAMED,
ARG_POS,
ARG_STAR,
ARG_STAR2,
IS_ABSTRACT,
AssignmentStmt,
Block,
BytesExpr,
CallExpr,
ClassDef,
ComparisonExpr,
Decorator,
EllipsisExpr,
Expression,
FloatExpr,
FuncBase,
FuncDef,
IfStmt,
Import,
ImportAll,
ImportFrom,
IndexExpr,
IntExpr,
ListExpr,
MemberExpr,
MypyFile,
NameExpr,
OverloadedFuncDef,
Statement,
StrExpr,
TupleExpr,
TypeInfo,
UnaryExpr,
)
from mypy.options import Options as MypyOptions
from mypy.stubdoc import Sig, find_unique_signatures, parse_all_signatures
from mypy.stubgenc import (
DocstringSignatureGenerator,
ExternalSignatureGenerator,
FallbackSignatureGenerator,
SignatureGenerator,
generate_stub_for_c_module,
)
from mypy.stubutil import (
CantImport,
common_dir_prefix,
fail_missing,
find_module_path_and_all_py3,
generate_guarded,
remove_misplaced_type_comments,
report_missing,
walk_packages,
)
from mypy.traverser import all_yield_expressions, has_return_statement, has_yield_expression
from mypy.types import (
OVERLOAD_NAMES,
AnyType,
CallableType,
Instance,
NoneType,
TupleType,
Type,
TypeList,
TypeStrVisitor,
UnboundType,
get_proper_type,
)
from mypy.visitor import NodeVisitor
TYPING_MODULE_NAMES: Final = ("typing", "typing_extensions")
# Common ways of naming package containing vendored modules.
VENDOR_PACKAGES: Final = ["packages", "vendor", "vendored", "_vendor", "_vendored_packages"]
# Avoid some file names that are unnecessary or likely to cause trouble (\n for end of path).
BLACKLIST: Final = [
"/six.py\n", # Likely vendored six; too dynamic for us to handle
"/vendored/", # Vendored packages
"/vendor/", # Vendored packages
"/_vendor/",
"/_vendored_packages/",
]
# Special-cased names that are implicitly exported from the stub (from m import y as y).
EXTRA_EXPORTED: Final = {
"pyasn1_modules.rfc2437.univ",
"pyasn1_modules.rfc2459.char",
"pyasn1_modules.rfc2459.univ",
}
# These names should be omitted from generated stubs.
IGNORED_DUNDERS: Final = {
"__all__",
"__author__",
"__version__",
"__about__",
"__copyright__",
"__email__",
"__license__",
"__summary__",
"__title__",
"__uri__",
"__str__",
"__repr__",
"__getstate__",
"__setstate__",
"__slots__",
}
# These methods are expected to always return a non-trivial value.
METHODS_WITH_RETURN_VALUE: Final = {
"__ne__",
"__eq__",
"__lt__",
"__le__",
"__gt__",
"__ge__",
"__hash__",
"__iter__",
}
# These magic methods always return the same type.
KNOWN_MAGIC_METHODS_RETURN_TYPES: Final = {
"__len__": "int",
"__length_hint__": "int",
"__init__": "None",
"__del__": "None",
"__bool__": "bool",
"__bytes__": "bytes",
"__format__": "str",
"__contains__": "bool",
"__complex__": "complex",
"__int__": "int",
"__float__": "float",
"__index__": "int",
}
class Options:
"""Represents stubgen options.
This class is mutable to simplify testing.
"""
def __init__(
self,
pyversion: tuple[int, int],
no_import: bool,
doc_dir: str,
search_path: list[str],
interpreter: str,
parse_only: bool,
ignore_errors: bool,
include_private: bool,
output_dir: str,
modules: list[str],
packages: list[str],
files: list[str],
verbose: bool,
quiet: bool,
export_less: bool,
) -> None:
# See parse_options for descriptions of the flags.
self.pyversion = pyversion
self.no_import = no_import
self.doc_dir = doc_dir
self.search_path = search_path
self.interpreter = interpreter
self.decointerpreter = interpreter
self.parse_only = parse_only
self.ignore_errors = ignore_errors
self.include_private = include_private
self.output_dir = output_dir
self.modules = modules
self.packages = packages
self.files = files
self.verbose = verbose
self.quiet = quiet
self.export_less = export_less
class StubSource:
"""A single source for stub: can be a Python or C module.
A simple extension of BuildSource that also carries the AST and
the value of __all__ detected at runtime.
"""
def __init__(
self, module: str, path: str | None = None, runtime_all: list[str] | None = None
) -> None:
self.source = BuildSource(path, module, None)
self.runtime_all = runtime_all
self.ast: MypyFile | None = None
@property
def module(self) -> str:
return self.source.module
@property
def path(self) -> str | None:
return self.source.path
# What was generated previously in the stub file. We keep track of these to generate
# nicely formatted output (add empty line between non-empty classes, for example).
EMPTY: Final = "EMPTY"
FUNC: Final = "FUNC"
CLASS: Final = "CLASS"
EMPTY_CLASS: Final = "EMPTY_CLASS"
VAR: Final = "VAR"
NOT_IN_ALL: Final = "NOT_IN_ALL"
# Indicates that we failed to generate a reasonable output
# for a given node. These should be manually replaced by a user.
ERROR_MARKER: Final = "<ERROR>"
class AnnotationPrinter(TypeStrVisitor):
"""Visitor used to print existing annotations in a file.
The main difference from TypeStrVisitor is a better treatment of
unbound types.
Notes:
* This visitor doesn't add imports necessary for annotations, this is done separately
by ImportTracker.
* It can print all kinds of types, but the generated strings may not be valid (notably
callable types) since it prints the same string that reveal_type() does.
* For Instance types it prints the fully qualified names.
"""
# TODO: Generate valid string representation for callable types.
# TODO: Use short names for Instances.
def __init__(self, stubgen: StubGenerator) -> None:
super().__init__()
self.stubgen = stubgen
def visit_any(self, t: AnyType) -> str:
s = super().visit_any(t)
self.stubgen.import_tracker.require_name(s)
return s
def visit_unbound_type(self, t: UnboundType) -> str:
s = t.name
self.stubgen.import_tracker.require_name(s)
if t.args:
s += f"[{self.args_str(t.args)}]"
return s
def visit_none_type(self, t: NoneType) -> str:
return "None"
def visit_type_list(self, t: TypeList) -> str:
return f"[{self.list_str(t.items)}]"
def args_str(self, args: Iterable[Type]) -> str:
"""Convert an array of arguments to strings and join the results with commas.
The main difference from list_str is the preservation of quotes for string
arguments
"""
types = ["builtins.bytes", "builtins.str"]
res = []
for arg in args:
arg_str = arg.accept(self)
if isinstance(arg, UnboundType) and arg.original_str_fallback in types:
res.append(f"'{arg_str}'")
else:
res.append(arg_str)
return ", ".join(res)
class AliasPrinter(NodeVisitor[str]):
"""Visitor used to collect type aliases _and_ type variable definitions.
Visit r.h.s of the definition to get the string representation of type alias.
"""
def __init__(self, stubgen: StubGenerator) -> None:
self.stubgen = stubgen
super().__init__()
def visit_call_expr(self, node: CallExpr) -> str:
# Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a
# type alias that has to be preserved (even if TypeVar is not the same as an alias)
callee = node.callee.accept(self)
args = []
for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds):
if kind == ARG_POS:
args.append(arg.accept(self))
elif kind == ARG_STAR:
args.append("*" + arg.accept(self))
elif kind == ARG_STAR2:
args.append("**" + arg.accept(self))
elif kind == ARG_NAMED:
args.append(f"{name}={arg.accept(self)}")
else:
raise ValueError(f"Unknown argument kind {kind} in call")
return f"{callee}({', '.join(args)})"
def visit_name_expr(self, node: NameExpr) -> str:
self.stubgen.import_tracker.require_name(node.name)
return node.name
def visit_member_expr(self, o: MemberExpr) -> str:
node: Expression = o
trailer = ""
while isinstance(node, MemberExpr):
trailer = "." + node.name + trailer
node = node.expr
if not isinstance(node, NameExpr):
return ERROR_MARKER
self.stubgen.import_tracker.require_name(node.name)
return node.name + trailer
def visit_str_expr(self, node: StrExpr) -> str:
return repr(node.value)
def visit_index_expr(self, node: IndexExpr) -> str:
base = node.base.accept(self)
index = node.index.accept(self)
return f"{base}[{index}]"
def visit_tuple_expr(self, node: TupleExpr) -> str:
return ", ".join(n.accept(self) for n in node.items)
def visit_list_expr(self, node: ListExpr) -> str:
return f"[{', '.join(n.accept(self) for n in node.items)}]"
def visit_ellipsis(self, node: EllipsisExpr) -> str:
return "..."
class ImportTracker:
"""Record necessary imports during stub generation."""
def __init__(self) -> None:
# module_for['foo'] has the module name where 'foo' was imported from, or None if
# 'foo' is a module imported directly; examples
# 'from pkg.m import f as foo' ==> module_for['foo'] == 'pkg.m'
# 'from m import f' ==> module_for['f'] == 'm'
# 'import m' ==> module_for['m'] == None
# 'import pkg.m' ==> module_for['pkg.m'] == None
# ==> module_for['pkg'] == None
self.module_for: dict[str, str | None] = {}
# direct_imports['foo'] is the module path used when the name 'foo' was added to the
# namespace.
# import foo.bar.baz ==> direct_imports['foo'] == 'foo.bar.baz'
# ==> direct_imports['foo.bar'] == 'foo.bar.baz'
# ==> direct_imports['foo.bar.baz'] == 'foo.bar.baz'
self.direct_imports: dict[str, str] = {}
# reverse_alias['foo'] is the name that 'foo' had originally when imported with an
# alias; examples
# 'import numpy as np' ==> reverse_alias['np'] == 'numpy'
# 'import foo.bar as bar' ==> reverse_alias['bar'] == 'foo.bar'
# 'from decimal import Decimal as D' ==> reverse_alias['D'] == 'Decimal'
self.reverse_alias: dict[str, str] = {}
# required_names is the set of names that are actually used in a type annotation
self.required_names: set[str] = set()
# Names that should be reexported if they come from another module
self.reexports: set[str] = set()
def add_import_from(self, module: str, names: list[tuple[str, str | None]]) -> None:
for name, alias in names:
if alias:
# 'from {module} import {name} as {alias}'
self.module_for[alias] = module
self.reverse_alias[alias] = name
else:
# 'from {module} import {name}'
self.module_for[name] = module
self.reverse_alias.pop(name, None)
self.direct_imports.pop(alias or name, None)
def add_import(self, module: str, alias: str | None = None) -> None:
if alias:
# 'import {module} as {alias}'
self.module_for[alias] = None
self.reverse_alias[alias] = module
else:
# 'import {module}'
name = module
# add module and its parent packages
while name:
self.module_for[name] = None
self.direct_imports[name] = module
self.reverse_alias.pop(name, None)
name = name.rpartition(".")[0]
def require_name(self, name: str) -> None:
self.required_names.add(name.split(".")[0])
def reexport(self, name: str) -> None:
"""Mark a given non qualified name as needed in __all__.
This means that in case it comes from a module, it should be
imported with an alias even is the alias is the same as the name.
"""
self.require_name(name)
self.reexports.add(name)
def import_lines(self) -> list[str]:
"""The list of required import lines (as strings with python code)."""
result = []
# To summarize multiple names imported from a same module, we collect those
# in the `module_map` dictionary, mapping a module path to the list of names that should
# be imported from it. the names can also be alias in the form 'original as alias'
module_map: Mapping[str, list[str]] = defaultdict(list)
for name in sorted(self.required_names):
# If we haven't seen this name in an import statement, ignore it
if name not in self.module_for:
continue
m = self.module_for[name]
if m is not None:
# This name was found in a from ... import ...
# Collect the name in the module_map
if name in self.reverse_alias:
name = f"{self.reverse_alias[name]} as {name}"
elif name in self.reexports:
name = f"{name} as {name}"
module_map[m].append(name)
else:
# This name was found in an import ...
# We can already generate the import line
if name in self.reverse_alias:
source = self.reverse_alias[name]
result.append(f"import {source} as {name}\n")
elif name in self.reexports:
assert "." not in name # Because reexports only has nonqualified names
result.append(f"import {name} as {name}\n")
else:
result.append(f"import {self.direct_imports[name]}\n")
# Now generate all the from ... import ... lines collected in module_map
for module, names in sorted(module_map.items()):
result.append(f"from {module} import {', '.join(sorted(names))}\n")
return result
def find_defined_names(file: MypyFile) -> set[str]:
finder = DefinitionFinder()
file.accept(finder)
return finder.names
class DefinitionFinder(mypy.traverser.TraverserVisitor):
"""Find names of things defined at the top level of a module."""
# TODO: Assignment statements etc.
def __init__(self) -> None:
# Short names of things defined at the top level.
self.names: set[str] = set()
def visit_class_def(self, o: ClassDef) -> None:
# Don't recurse into classes, as we only keep track of top-level definitions.
self.names.add(o.name)
def visit_func_def(self, o: FuncDef) -> None:
# Don't recurse, as we only keep track of top-level definitions.
self.names.add(o.name)
def find_referenced_names(file: MypyFile) -> set[str]:
finder = ReferenceFinder()
file.accept(finder)
return finder.refs
class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor):
"""Find all name references (both local and global)."""
# TODO: Filter out local variable and class attribute references
def __init__(self) -> None:
# Short names of things defined at the top level.
self.refs: set[str] = set()
def visit_block(self, block: Block) -> None:
if not block.is_unreachable:
super().visit_block(block)
def visit_name_expr(self, e: NameExpr) -> None:
self.refs.add(e.name)
def visit_instance(self, t: Instance) -> None:
self.add_ref(t.type.fullname)
super().visit_instance(t)
def visit_unbound_type(self, t: UnboundType) -> None:
if t.name:
self.add_ref(t.name)
def visit_tuple_type(self, t: TupleType) -> None:
# Ignore fallback
for item in t.items:
item.accept(self)
def visit_callable_type(self, t: CallableType) -> None:
# Ignore fallback
for arg in t.arg_types:
arg.accept(self)
t.ret_type.accept(self)
def add_ref(self, fullname: str) -> None:
self.refs.add(fullname.split(".")[-1])
class StubGenerator(mypy.traverser.TraverserVisitor):
"""Generate stub text from a mypy AST."""
def __init__(
self,
_all_: list[str] | None,
include_private: bool = False,
analyzed: bool = False,
export_less: bool = False,
) -> None:
# Best known value of __all__.
self._all_ = _all_
self._output: list[str] = []
self._decorators: list[str] = []
self._import_lines: list[str] = []
# Current indent level (indent is hardcoded to 4 spaces).
self._indent = ""
# Stack of defined variables (per scope).
self._vars: list[list[str]] = [[]]
# What was generated previously in the stub file.
self._state = EMPTY
self._toplevel_names: list[str] = []
self._include_private = include_private
self.import_tracker = ImportTracker()
# Was the tree semantically analysed before?
self.analyzed = analyzed
# Disable implicit exports of package-internal imports?
self.export_less = export_less
# Add imports that could be implicitly generated
self.import_tracker.add_import_from("typing", [("NamedTuple", None)])
# Names in __all__ are required
for name in _all_ or ():
if name not in IGNORED_DUNDERS:
self.import_tracker.reexport(name)
self.defined_names: set[str] = set()
# Short names of methods defined in the body of the current class
self.method_names: set[str] = set()
def visit_mypy_file(self, o: MypyFile) -> None:
self.module = o.fullname # Current module being processed
self.path = o.path
self.defined_names = find_defined_names(o)
self.referenced_names = find_referenced_names(o)
known_imports = {
"_typeshed": ["Incomplete"],
"typing": ["Any", "TypeVar"],
"collections.abc": ["Generator"],
}
for pkg, imports in known_imports.items():
for t in imports:
if t not in self.defined_names:
alias = None
else:
alias = "_" + t
self.import_tracker.add_import_from(pkg, [(t, alias)])
super().visit_mypy_file(o)
undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names]
if undefined_names:
if self._state != EMPTY:
self.add("\n")
self.add("# Names in __all__ with no definition:\n")
for name in sorted(undefined_names):
self.add(f"# {name}\n")
def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
"""@property with setters and getters, or @overload chain"""
overload_chain = False
for item in o.items:
if not isinstance(item, Decorator):
continue
if self.is_private_name(item.func.name, item.func.fullname):
continue
is_abstract, is_overload = self.process_decorator(item)
if not overload_chain:
self.visit_func_def(item.func, is_abstract=is_abstract, is_overload=is_overload)
if is_overload:
overload_chain = True
elif is_overload:
self.visit_func_def(item.func, is_abstract=is_abstract, is_overload=is_overload)
else:
# skip the overload implementation and clear the decorator we just processed
self.clear_decorators()
def visit_func_def(
self, o: FuncDef, is_abstract: bool = False, is_overload: bool = False
) -> None:
if (
self.is_private_name(o.name, o.fullname)
or self.is_not_in_all(o.name)
or (self.is_recorded_name(o.name) and not is_overload)
):
self.clear_decorators()
return
if not self._indent and self._state not in (EMPTY, FUNC) and not o.is_awaitable_coroutine:
self.add("\n")
if not self.is_top_level():
self_inits = find_self_initializers(o)
for init, value in self_inits:
if init in self.method_names:
# Can't have both an attribute and a method/property with the same name.
continue
init_code = self.get_init(init, value)
if init_code:
self.add(init_code)
# dump decorators, just before "def ..."
for s in self._decorators:
self.add(s)
self.clear_decorators()
self.add(f"{self._indent}{'async ' if o.is_coroutine else ''}def {o.name}(")
self.record_name(o.name)
args: list[str] = []
for i, arg_ in enumerate(o.arguments):
var = arg_.variable
kind = arg_.kind
name = var.name
annotated_type = (
o.unanalyzed_type.arg_types[i]
if isinstance(o.unanalyzed_type, CallableType)
else None
)
# I think the name check is incorrect: there are libraries which
# name their 0th argument other than self/cls
is_self_arg = i == 0 and name == "self"
is_cls_arg = i == 0 and name == "cls"
annotation = ""
if annotated_type and not is_self_arg and not is_cls_arg:
# Luckily, an argument explicitly annotated with "Any" has
# type "UnboundType" and will not match.
if not isinstance(get_proper_type(annotated_type), AnyType):
annotation = f": {self.print_annotation(annotated_type)}"
if kind.is_named() and not any(arg.startswith("*") for arg in args):
args.append("*")
if arg_.initializer:
if not annotation:
typename = self.get_str_type_of_node(arg_.initializer, True, False)
if typename == "":
annotation = "=..."
else:
annotation = f": {typename} = ..."
else:
annotation += " = ..."
arg = name + annotation
elif kind == ARG_STAR:
arg = f"*{name}{annotation}"
elif kind == ARG_STAR2:
arg = f"**{name}{annotation}"
else:
arg = name + annotation
args.append(arg)
retname = None
if o.name != "__init__" and isinstance(o.unanalyzed_type, CallableType):
if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType):
# Luckily, a return type explicitly annotated with "Any" has
# type "UnboundType" and will enter the else branch.
retname = None # implicit Any
else:
retname = self.print_annotation(o.unanalyzed_type.ret_type)
elif o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE:
# Always assume abstract methods return Any unless explicitly annotated. Also
# some dunder methods should not have a None return type.
retname = None # implicit Any
elif o.name in KNOWN_MAGIC_METHODS_RETURN_TYPES:
retname = KNOWN_MAGIC_METHODS_RETURN_TYPES[o.name]
elif has_yield_expression(o):
self.add_abc_import("Generator")
yield_name = "None"
send_name = "None"
return_name = "None"
for expr, in_assignment in all_yield_expressions(o):
if expr.expr is not None and not self.is_none_expr(expr.expr):
self.add_typing_import("Incomplete")
yield_name = "Incomplete"
if in_assignment:
self.add_typing_import("Incomplete")
send_name = "Incomplete"
if has_return_statement(o):
self.add_typing_import("Incomplete")
return_name = "Incomplete"
generator_name = self.typing_name("Generator")
retname = f"{generator_name}[{yield_name}, {send_name}, {return_name}]"
elif not has_return_statement(o) and not is_abstract:
retname = "None"
retfield = ""
if retname is not None:
retfield = " -> " + retname
self.add(", ".join(args))
self.add(f"){retfield}: ...\n")
self._state = FUNC
def is_none_expr(self, expr: Expression) -> bool:
return isinstance(expr, NameExpr) and expr.name == "None"
def visit_decorator(self, o: Decorator) -> None:
if self.is_private_name(o.func.name, o.func.fullname):
return
is_abstract, _ = self.process_decorator(o)
self.visit_func_def(o.func, is_abstract=is_abstract)
def process_decorator(self, o: Decorator) -> tuple[bool, bool]:
"""Process a series of decorators.
Only preserve certain special decorators such as @abstractmethod.
Return a pair of booleans:
- True if any of the decorators makes a method abstract.
- True if any of the decorators is typing.overload.
"""
is_abstract = False
is_overload = False
for decorator in o.original_decorators:
if isinstance(decorator, NameExpr):
i_is_abstract, i_is_overload = self.process_name_expr_decorator(decorator, o)
is_abstract = is_abstract or i_is_abstract
is_overload = is_overload or i_is_overload
elif isinstance(decorator, MemberExpr):
i_is_abstract, i_is_overload = self.process_member_expr_decorator(decorator, o)
is_abstract = is_abstract or i_is_abstract
is_overload = is_overload or i_is_overload
return is_abstract, is_overload
def process_name_expr_decorator(self, expr: NameExpr, context: Decorator) -> tuple[bool, bool]:
"""Process a function decorator of form @foo.
Only preserve certain special decorators such as @abstractmethod.
Return a pair of booleans:
- True if the decorator makes a method abstract.
- True if the decorator is typing.overload.
"""
is_abstract = False
is_overload = False
name = expr.name
if name in ("property", "staticmethod", "classmethod"):
self.add_decorator(name)
elif self.import_tracker.module_for.get(name) in (
"asyncio",
"asyncio.coroutines",
"types",
):
self.add_coroutine_decorator(context.func, name, name)
elif self.refers_to_fullname(name, "abc.abstractmethod"):
self.add_decorator(name)
self.import_tracker.require_name(name)
is_abstract = True
elif self.refers_to_fullname(name, "abc.abstractproperty"):
self.add_decorator("property")
self.add_decorator("abc.abstractmethod")
is_abstract = True
elif self.refers_to_fullname(name, OVERLOAD_NAMES):
self.add_decorator(name)
self.add_typing_import("overload")
is_overload = True
return is_abstract, is_overload
def refers_to_fullname(self, name: str, fullname: str | tuple[str, ...]) -> bool:
if isinstance(fullname, tuple):
return any(self.refers_to_fullname(name, fname) for fname in fullname)
module, short = fullname.rsplit(".", 1)
return self.import_tracker.module_for.get(name) == module and (
name == short or self.import_tracker.reverse_alias.get(name) == short
)
def process_member_expr_decorator(
self, expr: MemberExpr, context: Decorator
) -> tuple[bool, bool]:
"""Process a function decorator of form @foo.bar.
Only preserve certain special decorators such as @abstractmethod.
Return a pair of booleans:
- True if the decorator makes a method abstract.
- True if the decorator is typing.overload.
"""
is_abstract = False
is_overload = False
if expr.name == "setter" and isinstance(expr.expr, NameExpr):
self.add_decorator(f"{expr.expr.name}.setter")
elif (
isinstance(expr.expr, NameExpr)
and (
expr.expr.name == "abc"
or self.import_tracker.reverse_alias.get(expr.expr.name) == "abc"
)
and expr.name in ("abstractmethod", "abstractproperty")
):
if expr.name == "abstractproperty":
self.import_tracker.require_name(expr.expr.name)
self.add_decorator("%s" % ("property"))
self.add_decorator("{}.{}".format(expr.expr.name, "abstractmethod"))
else:
self.import_tracker.require_name(expr.expr.name)
self.add_decorator(f"{expr.expr.name}.{expr.name}")
is_abstract = True
elif expr.name == "coroutine":
if (
isinstance(expr.expr, MemberExpr)
and expr.expr.name == "coroutines"
and isinstance(expr.expr.expr, NameExpr)
and (
expr.expr.expr.name == "asyncio"
or self.import_tracker.reverse_alias.get(expr.expr.expr.name) == "asyncio"
)
):
self.add_coroutine_decorator(
context.func,
f"{expr.expr.expr.name}.coroutines.coroutine",
expr.expr.expr.name,
)
elif isinstance(expr.expr, NameExpr) and (
expr.expr.name in ("asyncio", "types")
or self.import_tracker.reverse_alias.get(expr.expr.name)
in ("asyncio", "asyncio.coroutines", "types")
):
self.add_coroutine_decorator(
context.func, expr.expr.name + ".coroutine", expr.expr.name
)
elif (
isinstance(expr.expr, NameExpr)
and (
expr.expr.name in TYPING_MODULE_NAMES
or self.import_tracker.reverse_alias.get(expr.expr.name) in TYPING_MODULE_NAMES
)
and expr.name == "overload"
):
self.import_tracker.require_name(expr.expr.name)
self.add_decorator(f"{expr.expr.name}.overload")
is_overload = True
return is_abstract, is_overload
def visit_class_def(self, o: ClassDef) -> None:
self.method_names = find_method_names(o.defs.body)
sep: int | None = None
if not self._indent and self._state != EMPTY:
sep = len(self._output)
self.add("\n")
self.add(f"{self._indent}class {o.name}")
self.record_name(o.name)
base_types = self.get_base_types(o)
if base_types:
for base in base_types:
self.import_tracker.require_name(base)
if isinstance(o.metaclass, (NameExpr, MemberExpr)):
meta = o.metaclass.accept(AliasPrinter(self))
base_types.append("metaclass=" + meta)
elif self.analyzed and o.info.is_protocol:
type_str = "Protocol"
if o.info.type_vars:
type_str += f'[{", ".join(o.info.type_vars)}]'
base_types.append(type_str)
self.add_typing_import("Protocol")
elif self.analyzed and o.info.is_abstract:
base_types.append("metaclass=abc.ABCMeta")
self.import_tracker.add_import("abc")
self.import_tracker.require_name("abc")
if base_types:
self.add(f"({', '.join(base_types)})")
self.add(":\n")
n = len(self._output)
self._indent += " "
self._vars.append([])
super().visit_class_def(o)
self._indent = self._indent[:-4]
self._vars.pop()
self._vars[-1].append(o.name)
if len(self._output) == n:
if self._state == EMPTY_CLASS and sep is not None:
self._output[sep] = ""
self._output[-1] = self._output[-1][:-1] + " ...\n"
self._state = EMPTY_CLASS
else:
self._state = CLASS
self.method_names = set()
def get_base_types(self, cdef: ClassDef) -> list[str]:
"""Get list of base classes for a class."""
base_types: list[str] = []
for base in cdef.base_type_exprs:
if isinstance(base, NameExpr):
if base.name != "object":
base_types.append(base.name)
elif isinstance(base, MemberExpr):
modname = get_qualified_name(base.expr)
base_types.append(f"{modname}.{base.name}")
elif isinstance(base, IndexExpr):
p = AliasPrinter(self)
base_types.append(base.accept(p))
return base_types
def visit_block(self, o: Block) -> None:
# Unreachable statements may be partially uninitialized and that may
# cause trouble.
if not o.is_unreachable:
super().visit_block(o)
def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
foundl = []
for lvalue in o.lvalues:
if isinstance(lvalue, NameExpr) and self.is_namedtuple(o.rvalue):
assert isinstance(o.rvalue, CallExpr)
self.process_namedtuple(lvalue, o.rvalue)
continue
if (
self.is_top_level()
and isinstance(lvalue, NameExpr)
and not self.is_private_name(lvalue.name)