Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c05b244

Browse files
ddfishergvanrossum
authored andcommitted
Fully annotate stubgen (python#2667)
1 parent b6935f4 commit c05b244

4 files changed

Lines changed: 47 additions & 33 deletions

File tree

mypy.ini

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,6 @@
22
disallow_untyped_defs = True
33

44
; historical exceptions
5-
[mypy-mypy.stubgen]
6-
disallow_untyped_defs = False
7-
8-
[mypy-mypy.stubutil]
9-
disallow_untyped_defs = False
10-
11-
[mypy-mypy.stubgenc]
12-
disallow_untyped_defs = False
13-
145
[mypy-mypy.test.testextensions]
156
disallow_untyped_defs = False
167

mypy/stubgen.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@
4545
import sys
4646
import textwrap
4747

48-
from typing import Any, List, Dict, Tuple, Iterable, Optional, NamedTuple, Set
48+
from typing import (
49+
Any, List, Dict, Tuple, Iterable, Iterator, Optional, NamedTuple, Set, Union, cast
50+
)
4951

5052
import mypy.build
5153
import mypy.parse
@@ -341,6 +343,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
341343

342344
for lvalue in o.lvalues:
343345
if isinstance(lvalue, NameExpr) and self.is_namedtuple(o.rvalue):
346+
assert isinstance(o.rvalue, CallExpr)
344347
self.process_namedtuple(lvalue, o.rvalue)
345348
continue
346349
if isinstance(lvalue, TupleExpr):
@@ -374,15 +377,15 @@ def is_namedtuple(self, expr: Expression) -> bool:
374377
return ((isinstance(callee, NameExpr) and callee.name.endswith('namedtuple')) or
375378
(isinstance(callee, MemberExpr) and callee.name == 'namedtuple'))
376379

377-
def process_namedtuple(self, lvalue, rvalue):
380+
def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
378381
self.add_import_line('from collections import namedtuple\n')
379382
if self._state != EMPTY:
380383
self.add('\n')
381384
name = repr(getattr(rvalue.args[0], 'value', '<ERROR>'))
382385
if isinstance(rvalue.args[1], StrExpr):
383386
items = repr(rvalue.args[1].value)
384387
elif isinstance(rvalue.args[1], ListExpr):
385-
list_items = rvalue.args[1].items
388+
list_items = cast(List[StrExpr], rvalue.args[1].items)
386389
items = '[%s]' % ', '.join(repr(item.value) for item in list_items)
387390
else:
388391
items = '<ERROR>'
@@ -585,7 +588,7 @@ def get_qualified_name(o: Expression) -> str:
585588
return '<ERROR>'
586589

587590

588-
def walk_packages(packages: List[str]):
591+
def walk_packages(packages: List[str]) -> Iterator[str]:
589592
for package_name in packages:
590593
package = __import__(package_name)
591594
yield package.__name__

mypy/stubgenc.py

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,34 @@
66
import importlib
77
import os.path
88
import re
9-
9+
from typing import List, Dict, Tuple
10+
from types import ModuleType
1011

1112
from mypy.stubutil import (
1213
parse_all_signatures, find_unique_signatures, is_c_module, write_header,
1314
infer_sig_from_docstring
1415
)
1516

1617

17-
def generate_stub_for_c_module(module_name, target, add_header=True, sigs={}, class_sigs={}):
18+
def generate_stub_for_c_module(module_name: str,
19+
target: str,
20+
add_header: bool = True,
21+
sigs: Dict[str, str] = {},
22+
class_sigs: Dict[str, str] = {},
23+
) -> None:
1824
module = importlib.import_module(module_name)
1925
assert is_c_module(module), '%s is not a C module' % module_name
2026
subdir = os.path.dirname(target)
2127
if subdir and not os.path.isdir(subdir):
2228
os.makedirs(subdir)
23-
functions = []
29+
functions = [] # type: List[str]
2430
done = set()
2531
items = sorted(module.__dict__.items(), key=lambda x: x[0])
2632
for name, obj in items:
2733
if is_c_function(obj):
2834
generate_c_function_stub(module, name, obj, functions, sigs=sigs)
2935
done.add(name)
30-
types = []
36+
types = [] # type: List[str]
3137
for name, obj in items:
3238
if name.startswith('__') and name.endswith('__'):
3339
continue
@@ -62,7 +68,7 @@ def generate_stub_for_c_module(module_name, target, add_header=True, sigs={}, cl
6268
file.write('%s\n' % line)
6369

6470

65-
def add_typing_import(output):
71+
def add_typing_import(output: List[str]) -> List[str]:
6672
names = []
6773
for name in ['Any']:
6874
if any(re.search(r'\b%s\b' % name, line) for line in output):
@@ -73,27 +79,34 @@ def add_typing_import(output):
7379
return output[:]
7480

7581

76-
def is_c_function(obj):
82+
def is_c_function(obj: object) -> bool:
7783
return type(obj) is type(ord)
7884

7985

80-
def is_c_method(obj):
86+
def is_c_method(obj: object) -> bool:
8187
return type(obj) in (type(str.index),
8288
type(str.__add__),
8389
type(str.__new__))
8490

8591

86-
def is_c_classmethod(obj):
92+
def is_c_classmethod(obj: object) -> bool:
8793
type_str = type(obj).__name__
8894
return type_str == 'classmethod_descriptor'
8995

9096

91-
def is_c_type(obj):
97+
def is_c_type(obj: object) -> bool:
9298
return type(obj) is type(int)
9399

94100

95-
def generate_c_function_stub(module, name, obj, output, self_var=None, sigs={}, class_name=None,
96-
class_sigs={}):
101+
def generate_c_function_stub(module: ModuleType,
102+
name: str,
103+
obj: object,
104+
output: List[str],
105+
self_var: str = None,
106+
sigs: Dict[str, str] = {},
107+
class_name: str = None,
108+
class_sigs: Dict[str, str] = {},
109+
) -> None:
97110
if self_var:
98111
self_arg = '%s, ' % self_var
99112
else:
@@ -117,7 +130,13 @@ def generate_c_function_stub(module, name, obj, output, self_var=None, sigs={},
117130
output.append('def %s(%s%s): ...' % (name, self_arg, sig))
118131

119132

120-
def generate_c_type_stub(module, class_name, obj, output, sigs={}, class_sigs={}):
133+
def generate_c_type_stub(module: ModuleType,
134+
class_name: str,
135+
obj: type,
136+
output: List[str],
137+
sigs: Dict[str, str] = {},
138+
class_sigs: Dict[str, str] = {},
139+
) -> None:
121140
items = sorted(obj.__dict__.items(), key=lambda x: method_name_sort_key(x[0]))
122141
methods = []
123142
done = set()
@@ -151,7 +170,7 @@ def generate_c_type_stub(module, class_name, obj, output, sigs={}, class_sigs={}
151170
# TODO: Is this always object?
152171
del all_bases[-1]
153172
# Remove base classes of other bases as redundant.
154-
bases = []
173+
bases = [] # type: List[type]
155174
for base in all_bases:
156175
if not any(issubclass(b, base) for b in bases):
157176
bases.append(base)
@@ -169,15 +188,15 @@ def generate_c_type_stub(module, class_name, obj, output, sigs={}, class_sigs={}
169188
output.append(' %s' % method)
170189

171190

172-
def method_name_sort_key(name):
191+
def method_name_sort_key(name: str) -> Tuple[int, str]:
173192
if name in ('__new__', '__init__'):
174193
return (0, name)
175194
if name.startswith('__') and name.endswith('__'):
176195
return (2, name)
177196
return (1, name)
178197

179198

180-
def is_skipped_attribute(attr):
199+
def is_skipped_attribute(attr: str) -> bool:
181200
return attr in ('__getattribute__',
182201
'__str__',
183202
'__repr__',
@@ -187,7 +206,7 @@ def is_skipped_attribute(attr):
187206
'__weakref__') # For pickling
188207

189208

190-
def infer_method_sig(name):
209+
def infer_method_sig(name: str) -> str:
191210
if name.startswith('__') and name.endswith('__'):
192211
name = name[2:-2]
193212
if name in ('hash', 'iter', 'next', 'sizeof', 'copy', 'deepcopy', 'reduce', 'getinitargs',

mypy/stubutil.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import re
22
import sys
33

4-
from typing import Any, Optional, Tuple, Sequence, MutableSequence, List, MutableMapping
4+
from typing import Any, Optional, Tuple, Sequence, MutableSequence, List, MutableMapping, IO
5+
from types import ModuleType
56

67

78
# Type Alias for Signatures
@@ -85,11 +86,11 @@ def find_unique_signatures(sigs: Sequence[Sig]) -> List[Sig]:
8586
return sorted(result)
8687

8788

88-
def is_c_module(module):
89+
def is_c_module(module: ModuleType) -> bool:
8990
return '__file__' not in module.__dict__ or module.__dict__['__file__'].endswith('.so')
9091

9192

92-
def write_header(file, module_name, pyversion=(3, 5)):
93+
def write_header(file: IO[str], module_name: str, pyversion: Tuple[int, int] = (3, 5)) -> None:
9394
if module_name:
9495
if pyversion[0] >= 3:
9596
version = '%d.%d' % (sys.version_info.major,
@@ -102,7 +103,7 @@ def write_header(file, module_name, pyversion=(3, 5)):
102103
'# NOTE: This dynamically typed stub was automatically generated by stubgen.\n\n')
103104

104105

105-
def infer_sig_from_docstring(docstr, name):
106+
def infer_sig_from_docstring(docstr: str, name: str) -> Optional[str]:
106107
if not docstr:
107108
return None
108109
docstr = docstr.lstrip()

0 commit comments

Comments
 (0)