Skip to content

Commit ab25c53

Browse files
committed
fixes
1 parent 7c066f3 commit ab25c53

File tree

6 files changed

+22
-38
lines changed

6 files changed

+22
-38
lines changed

docs/source/stubgen.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ alter the default behavior:
139139

140140
Import and inspect modules instead of parsing source code. This is the default
141141
behavior for c modules and pyc-only packages. The flag is useful to force
142-
inspection for pure python modules that make use of dynamically generated
143-
members that would otherwiswe be omitted when using the default behavior of
142+
inspection for pure python modules that make use of dynamically generated
143+
members that would otherwiswe be omitted when using the default behavior of
144144
code parsing. Implies :option:`--no-analysis` as analysis requires source
145145
code.
146146

mypy/stubgen.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,12 @@
4242
from __future__ import annotations
4343

4444
import argparse
45-
import glob
4645
import keyword
4746
import os
4847
import os.path
4948
import sys
5049
import traceback
51-
from collections import defaultdict
52-
from typing import Final, Iterable, Mapping
53-
from typing_extensions import Final
50+
from typing import Final, Iterable
5451

5552
import mypy.build
5653
import mypy.mixedtraverser
@@ -113,10 +110,10 @@
113110
from mypy.stubdoc import ArgSig, FunctionSig
114111
from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module
115112
from mypy.stubutil import (
113+
BaseStubGenerator,
116114
CantImport,
117115
ClassInfo,
118116
FunctionContext,
119-
BaseStubGenerator,
120117
common_dir_prefix,
121118
fail_missing,
122119
find_module_path_and_all_py3,
@@ -735,19 +732,20 @@ def get_base_types(self, cdef: ClassDef) -> list[str]:
735732
typename = base.args[0].value
736733
if nt_fields is not None:
737734
fields_str = ", ".join(f"({f!r}, {t})" for f, t in nt_fields)
738-
namedtuple_name = self.typing_name("NamedTuple")
735+
namedtuple_name = self.add_typing_import("NamedTuple")
739736
base_types.append(f"{namedtuple_name}({typename!r}, [{fields_str}])")
740737
self.add_typing_import("NamedTuple")
741738
else:
742739
# Invalid namedtuple() call, cannot determine fields
743-
base_types.append(self.typing_name("Incomplete"))
740+
base_types.append(
741+
self.add_obj_import("_typeshed", "Incomplete", require=True)
742+
)
744743
elif self.is_typed_namedtuple(base):
745744
base_types.append(base.accept(p))
746745
else:
747746
# At this point, we don't know what the base class is, so we
748747
# just use Incomplete as the base class.
749-
base_types.append(self.typing_name("Incomplete"))
750-
self.add_typing_import("Incomplete")
748+
base_types.append(self.add_obj_import("_typeshed", "Incomplete", require=True))
751749
for name, value in cdef.keywords.items():
752750
if name == "metaclass":
753751
continue # handled separately
@@ -860,8 +858,7 @@ def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
860858
if fields is None:
861859
self.annotate_as_incomplete(lvalue)
862860
return
863-
self.add_typing_import("NamedTuple")
864-
bases = self.typing_name("NamedTuple")
861+
bases = self.add_typing_import("NamedTuple")
865862
# TODO: Add support for generic NamedTuples. Requires `Generic` as base class.
866863
class_def = f"{self._indent}class {lvalue.name}({bases}):"
867864
if len(fields) == 0:
@@ -918,8 +915,7 @@ def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
918915
self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
919916
self._state = VAR
920917
else:
921-
incomplete = self.add_obj_import("_typeshed", "Incomplete", require=True)
922-
bases = self.typing_name("TypedDict")
918+
bases = self.add_typing_import("TypedDict")
923919
# TODO: Add support for generic TypedDicts. Requires `Generic` as base class.
924920
if total is not None:
925921
bases += f", total={total.accept(p)}"
@@ -936,8 +932,8 @@ def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
936932
self._state = CLASS
937933

938934
def annotate_as_incomplete(self, lvalue: NameExpr) -> None:
939-
self.add_typing_import("Incomplete")
940-
self.add(f"{self._indent}{lvalue.name}: {self.typing_name('Incomplete')}\n")
935+
incomplete = self.add_obj_import("_typeshed", "Incomplete", require=True)
936+
self.add(f"{self._indent}{lvalue.name}: {incomplete}\n")
941937
self._state = VAR
942938

943939
def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:

mypy/stubgenc.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,8 @@
1111
import inspect
1212
import keyword
1313
import os.path
14-
import re
15-
from abc import abstractmethod
1614
from types import FunctionType, ModuleType
17-
from typing import Any, Final, Mapping
15+
from typing import Any, Mapping
1816

1917
from mypy.fastparse import parse_type_comment
2018
from mypy.moduleinspect import is_c_module
@@ -31,10 +29,10 @@
3129
parse_all_signatures,
3230
)
3331
from mypy.stubutil import (
32+
BaseStubGenerator,
3433
ClassInfo,
3534
FunctionContext,
3635
SignatureGenerator,
37-
BaseStubGenerator,
3836
infer_method_ret_type,
3937
)
4038

@@ -587,7 +585,7 @@ def _fix_iter(
587585
ctx.class_info
588586
and ctx.class_info.cls is not None
589587
and ctx.name == "__getitem__"
590-
and "__iter__" not in getattr(ctx.class_info.cls, "__dict__")
588+
and "__iter__" not in ctx.class_info.cls.__dict__
591589
):
592590
item_type: str | None = None
593591
for sig in inferred:

mypy/stubutil.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from __future__ import annotations
44

5-
import keyword
65
import os.path
76
import re
87
import sys
@@ -657,9 +656,9 @@ def set_defined_names(self, defined_names: set[str]) -> None:
657656
# a corresponding import statement.
658657
known_imports = {
659658
"_typeshed": ["Incomplete"],
660-
"typing": ["Any", "TypeVar", "ParamSpec", "NamedTuple"],
659+
"typing": ["Any", "TypeVar", "NamedTuple"],
661660
"collections.abc": ["Generator"],
662-
"typing_extensions": ["TypedDict"],
661+
"typing_extensions": ["TypedDict", "ParamSpec", "TypeVarTuple"],
663662
}
664663
for pkg, imports in known_imports.items():
665664
for t in imports:

mypy/test/teststubgen.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,6 @@ def test(cls, arg0: str) -> None:
918918
pass
919919

920920
output: list[str] = []
921-
imports: list[str] = []
922921
mod = ModuleType(TestClass.__module__, "")
923922
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
924923
gen.generate_function_stub(
@@ -1095,19 +1094,11 @@ def test(arg0: str) -> None:
10951094
test.__doc__ = property(lambda self: "test(arg0: str) -> None") # type: ignore[assignment]
10961095

10971096
output: list[str] = []
1098-
imports: list[str] = []
10991097
mod = ModuleType(self.__module__, "")
1100-
generate_c_function_stub(
1101-
mod,
1102-
"test",
1103-
test,
1104-
output=output,
1105-
imports=imports,
1106-
known_modules=[mod.__name__],
1107-
sig_generators=get_sig_generators(parse_options([])),
1108-
)
1098+
gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)
1099+
gen.generate_function_stub("test", test, output=output)
11091100
assert_equal(output, ["def test(*args, **kwargs) -> Any: ..."])
1110-
assert_equal(imports, [])
1101+
assert_equal(gen.get_imports().splitlines(), [])
11111102

11121103
def test_generate_c_property_with_pybind11(self) -> None:
11131104
"""Signatures included by PyBind11 inside property.fget are read."""

test-data/unit/stubgen.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2853,7 +2853,7 @@ __uri__ = ''
28532853
__version__ = ''
28542854

28552855
[out]
2856-
from m import __version__ as __version__
2856+
from m import __version__ as __version__
28572857

28582858
class A: ...
28592859

0 commit comments

Comments
 (0)