Skip to content

Commit 5e817cd

Browse files
Stubtest: clean up the _belongs_to_runtime function (#14361)
There's a small semantic change in this PR (instead of returning `False` if trying to access the `__module__` attribute raises an exception, we now just move on to the next heuristic). But the main purpose of this PR is to make the code more readable, as this function was getting quite hard to understand. Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
1 parent 9dc624b commit 5e817cd

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

mypy/stubtest.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -346,16 +346,20 @@ def verify_mypyfile(
346346
imported_symbols = _get_imported_symbol_names(runtime)
347347

348348
def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
349+
"""Heuristics to determine whether a name originates from another module."""
349350
obj = getattr(r, attr)
350351
if isinstance(obj, types.ModuleType):
351352
return False
352353
if callable(obj):
354+
# It's highly likely to be a class or a function if it's callable,
355+
# so the __module__ attribute will give a good indication of which module it comes from
353356
try:
354-
obj_mod = getattr(obj, "__module__", None)
357+
obj_mod = obj.__module__
355358
except Exception:
356-
return False
357-
if obj_mod is not None:
358-
return bool(obj_mod == r.__name__)
359+
pass
360+
else:
361+
if isinstance(obj_mod, str):
362+
return bool(obj_mod == r.__name__)
359363
if imported_symbols is not None:
360364
return attr not in imported_symbols
361365
return True
@@ -367,8 +371,9 @@ def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
367371
m
368372
for m in dir(runtime)
369373
if not is_probably_private(m)
370-
# Ensure that the object's module is `runtime`, since in the absence of __all__ we
371-
# don't have a good way to detect re-exports at runtime.
374+
# Filter out objects that originate from other modules (best effort). Note that in the
375+
# absence of __all__, we don't have a way to detect explicit / intentional re-exports
376+
# at runtime
372377
and _belongs_to_runtime(runtime, m)
373378
}
374379
)

0 commit comments

Comments
 (0)