diff --git a/mypy/stubgen.py b/mypy/stubgen.py index f074a34d5c64..ece22ba235bf 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -633,6 +633,11 @@ def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: new_args = infer_method_arg_types( ctx.name, ctx.class_info.self_var, [arg.name for arg in args] ) + + if ctx.name == "__exit__": + self.import_tracker.add_import("types") + self.import_tracker.require_name("types") + if new_args is not None: args = new_args diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test index 717137cbd251..b4c66c2e5853 100644 --- a/test-data/unit/stubgen.test +++ b/test-data/unit/stubgen.test @@ -3777,6 +3777,8 @@ class MatchNames: def __exit__(self, type, value, traceback): ... [out] +import types + class MismatchNames: def __exit__(self, tp: type[BaseException] | None, val: BaseException | None, tb: types.TracebackType | None) -> None: ...