Skip to content
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

Stubtest: Improve heuristics for determining whether global-namespace names are imported #14270

Merged
merged 3 commits into from
Dec 22, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
48 changes: 42 additions & 6 deletions mypy/stubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import os
import pkgutil
import re
import symtable
import sys
import traceback
import types
Expand Down Expand Up @@ -281,6 +282,34 @@ def _verify_exported_names(
)


def _get_imported_symbol_names(runtime: types.ModuleType) -> frozenset[str] | None:
"""Retrieve the names in the global namespace which are known to be imported.

1). Use inspect to retrieve the source code of the module
2). Use symtable to parse the source and retrieve names that are known to be imported
from other modules.

If either of the above steps fails, return `None`.

Note that if a set of names is returned,
it won't include names imported via `from foo import *` imports.
"""
try:
source = inspect.getsource(runtime)
except (OSError, TypeError, SyntaxError):
return None

if not source.strip():
return None
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved

try:
module_symtable = symtable.symtable(source, runtime.__name__, "exec")
except SyntaxError:
return None

return frozenset(sym.get_name() for sym in module_symtable.get_symbols() if sym.is_imported())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like if you have an import and an assignment, is_imported is still True. I think this is probably desirable, given that we usually type objects as coming from their C accelerator modules even if there is a pure Python equivalent. So no action item here, just typing out my thoughts :-)



@verify.register(nodes.MypyFile)
def verify_mypyfile(
stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]
Expand Down Expand Up @@ -310,15 +339,22 @@ def verify_mypyfile(
if not o.module_hidden and (not is_probably_private(m) or hasattr(runtime, m))
}

imported_symbols = _get_imported_symbol_names(runtime)

def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
obj = getattr(r, attr)
try:
obj_mod = getattr(obj, "__module__", None)
except Exception:
if isinstance(obj, types.ModuleType):
return False
if obj_mod is not None:
return bool(obj_mod == r.__name__)
return not isinstance(obj, types.ModuleType)
if callable(obj):
try:
obj_mod = getattr(obj, "__module__", None)
except Exception:
return False
if obj_mod is not None:
return bool(obj_mod == r.__name__)
if imported_symbols is not None:
return attr not in imported_symbols
return True

runtime_public_contents = (
runtime_all_as_set
Expand Down
3 changes: 3 additions & 0 deletions mypy/test/teststubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,9 @@ def test_missing_no_runtime_all(self) -> Iterator[Case]:
yield Case(stub="", runtime="import sys", error=None)
yield Case(stub="", runtime="def g(): ...", error="g")
yield Case(stub="", runtime="CONSTANT = 0", error="CONSTANT")
yield Case(stub="", runtime="import re; constant = re.compile('foo')", error="constant")
yield Case(stub="", runtime="from json.scanner import NUMBER_RE", error=None)
yield Case(stub="", runtime="from string import ascii_letters", error=None)

@collect_cases
def test_non_public_1(self) -> Iterator[Case]:
Expand Down