Skip to content

Stubtest: do not error if a function is async in the stub, but not at runtime #12234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 8 additions & 21 deletions mypy/stubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,18 +700,6 @@ def _verify_signature(
yield 'runtime does not have **kwargs argument "{}"'.format(stub.varkw.variable.name)


def _verify_coroutine(
stub: nodes.FuncItem, runtime: Any, *, runtime_is_coroutine: bool
) -> Optional[str]:
if stub.is_coroutine:
if not runtime_is_coroutine:
return 'is an "async def" function in the stub, but not at runtime'
else:
if runtime_is_coroutine:
return 'is an "async def" function at runtime, but not in the stub'
return None


@verify.register(nodes.FuncItem)
def verify_funcitem(
stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: List[str]
Expand All @@ -735,21 +723,20 @@ def verify_funcitem(
stub_sig = Signature.from_funcitem(stub)
runtime_sig = Signature.from_inspect_signature(signature)
runtime_sig_desc = f'{"async " if runtime_is_coroutine else ""}def {signature}'
stub_desc = f'def {stub_sig!r}'
else:
runtime_sig_desc = None

coroutine_mismatch_error = _verify_coroutine(
stub,
runtime,
runtime_is_coroutine=runtime_is_coroutine
)
runtime_sig_desc, stub_desc = None, None

if coroutine_mismatch_error is not None:
# Don't raise an error if the stub is a coroutine, but the runtime isn't.
# That results in false positives.
# See https://github.com/python/typeshed/issues/7344
if runtime_is_coroutine and not stub.is_coroutine:
yield Error(
object_path,
coroutine_mismatch_error,
'is an "async def" function at runtime, but not in the stub',
stub,
runtime,
stub_desc=stub_desc,
runtime_desc=runtime_sig_desc
)

Expand Down
11 changes: 6 additions & 5 deletions mypy/test/teststubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,17 @@ class X:

@collect_cases
def test_coroutines(self) -> Iterator[Case]:
yield Case(
stub="async def foo() -> int: ...",
runtime="def foo(): return 5",
error="foo",
)
yield Case(
stub="def bar() -> int: ...",
runtime="async def bar(): return 5",
error="bar",
)
# Don't error for this one -- we get false positives otherwise
yield Case(
stub="async def foo() -> int: ...",
runtime="def foo(): return 5",
error=None,
)
yield Case(
stub="def baz() -> int: ...",
runtime="def baz(): return 5",
Expand Down