Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): type Python receivers through properties and returned objects (#3666)

Swati Ahujacd40f86babc3
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
index 17e7ebf91..c7b87d4cb 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -5,10 +5,12 @@ from __future__ import annotations
import posixpath
import re
from bisect import bisect_left, bisect_right
+from collections import Counter
from dataclasses import replace
from pathlib import Path
from typing import NamedTuple, TypeVar
+from .decorator_names import is_property_accessor, is_property_getter
from .lang_helpers.anonymous_classes import is_anonymous_member
from .languages.receiver_types import (
BINDING_LANGUAGES,
@@ -726,19 +728,40 @@ class ReceiverTypingMixin:
type_name, _, typing_file = self._receiver_type_and_scope(
file_path, caller_id, language, head
)
+ if type_name is not None and language == "python" and "::" in type_name:
+ return self._located(file_path, type_name) # typed from a call
return None if type_name is None else self._class_named(typing_file, type_name)
def _chain_hop(
self, found: tuple[str, str, str], field: str, language: str
) -> tuple[str, str, str] | None:
- """The class *field* of *found*'s class holds, tiered by the weaker hop."""
+ """The class *field* of *found*'s class holds, tiered by the weaker hop.
+
+ A Python field no assignment types may be a ``@property``, typed by its
+ getter's return annotation.
+ """
class_file, class_id, tier = found
- type_name = self._field_types_in(class_file, language).get(class_id, {}).get(field)
- hop = None if type_name is None else self._class_named(class_file, type_name)
+ fields = self._field_types_in(class_file, language).get(class_id, {})
+ if field in fields:
+ type_name = fields[field]
+ hop = None if type_name is None else self._class_named(class_file, type_name)
+ elif language == "python":
+ hop = self._located(class_file, self._property_type_id(class_file, class_id, field))
+ else:
+ hop = None
if hop is None:
return None
return hop[0], hop[1], max(tier, hop[2], key=_CHAIN_TIER_RANK.__getitem__)
+ def _located(self, file_path: str, type_id: str | None) -> tuple[str, str, str] | None:
+ """``(file, class id, tier)`` for a class already known by id, seen from *file_path*."""
+ if type_id is None:
+ return None
+ path = self._symbol_paths_by_id.get(type_id)
+ if path is None:
+ return None
+ return path, type_id, "same_file" if path == file_path else "import"
+
def _class_named(self, file_path: str, type_name: str) -> tuple[str, str, str] | None:
"""``(file, class id, tier)`` for the one class *type_name* names in *file_path*.
@@ -1099,31 +1122,69 @@ class ReceiverTypingMixin:
only a second ``:=`` of the name (another block) can disagree, and
that makes the name unanswerable, as for any declaration. A name a
declaration already types keeps that reading untouched.
+
+ A Python name may be rebound to anything, so one the body also binds
+ other than by a call assignment is skipped, and one whose call
+ assignments do not all yield a type is unanswerable.
"""
assignments = self._call_assignments_for(file_path, language)
sites = self._call_sites_for(file_path)
declared = frozenset(types)
first = bisect_left(assignments, start, key=lambda a: a.line)
- for assignment in assignments[first:]:
- if assignment.line > end:
- break
- if assignment.name in declared:
+ in_body = [a for a in assignments[first:] if a.line <= end]
+ rebound = self._rebound_names(file_path, language, in_body, (start, end))
+ for assignment in in_body:
+ if assignment.name in declared or assignment.name in rebound:
continue
site = sites.get((assignment.line, assignment.receiver, assignment.target))
- resolved = None if site is None else self._resolve_one(file_path, site)
- # A repo-wide guess at the callee is not evidence of what it returns.
- if resolved is None or "global" in resolved.origin:
- continue
- type_id = self._returned_type_id(resolved.callee_id)
+ type_id = (
+ None
+ if site is None
+ else self._site_returned_type_id(file_path, site, assignment.awaited)
+ )
if type_id is not None:
record_type(types, assignment.name, type_id)
+ elif language == "python":
+ types[assignment.name] = None
+
+ def _rebound_names(
+ self,
+ file_path: str,
+ language: str,
+ assignments: list[CallAssignment],
+ span: tuple[int, int],
+ ) -> set[str]:
+ """Names the body binds anywhere but in one of its call *assignments*.
+
+ Counted by position, so a second binding on an assignment's own line counts.
+ """
+ assigned = Counter((a.line, a.name) for a in assignments)
+ bound = Counter(
+ (line, name)
+ for line, _, name in self._binding_positions_for(file_path, language)
+ if span[0] <= line <= span[1]
+ )
+ return {name for (line, name), count in bound.items() if count > assigned[(line, name)]}
- def _returned_type_id(self, callee_id: str) -> str | None:
+ def _site_returned_type_id(self, file_path: str, site: CallSite, awaited: bool) -> str | None:
+ """The type id the call at *site* returns, read off the callee it resolves to."""
+ resolved = self._resolve_one(file_path, site)
+ # A repo-wide guess at the callee is not evidence of what it returns.
+ if resolved is None or "global" in resolved.origin:
+ return None
+ return self._returned_type_id(resolved.callee_id, awaited)
+
+ def _returned_type_id(self, callee_id: str, awaited: bool = False) -> str | None:
"""The repository type a go call to *callee_id* yields, as a symbol id.
``T`` is looked up in the callee's own package and ``pkg.T`` in the
package the callee's file imports as ``pkg``; exactly one type there
must carry the name. A slice, map or external type yields None.
+
+ A Python return annotation must be one bare class name, quoted or not,
+ read in the callee's file as a chain hop reads a field's type. A
+ property is read, not called, and an ``async def`` returns a coroutine
+ unless the call is *awaited*.
"""
symbol = self._symbols_by_id.get(callee_id)
path = self._symbol_paths_by_id.get(callee_id)
@@ -1131,6 +1192,14 @@ class ReceiverTypingMixin:
return None
if symbol.kind in _TYPE_KINDS:
return callee_id # a conversion, ``T(x)``
+ if symbol.language != "python":
+ return self._go_returned_type_id(symbol, path)
+ if is_property_accessor(symbol.decorators) or (symbol.is_async and not awaited):
+ return None
+ return self._python_returned_class(symbol, path)
+
+ def _go_returned_type_id(self, symbol: Symbol, path: str) -> str | None:
+ """``_returned_type_id`` for a go function or method *symbol* declared in *path*."""
raw = declared_return_type(symbol.signature or "")
written = go_first_result(raw).lstrip("*") if raw else ""
type_name = bare_type_name(written)
@@ -1139,8 +1208,10 @@ class ReceiverTypingMixin:
if not type_name.isidentifier() or (qualifier and not qualifier.isidentifier()):
return None
package = posixpath.dirname(path) if not qualifier else self._imported_dir(path, qualifier)
- if package is None:
- return None
+ return None if package is None else self._only_type_in_dir(type_name, package)
+
+ def _only_type_in_dir(self, type_name: str, package: str) -> str | None:
+ """The id of the one type named *type_name* declared in the directory *package*."""
found = [
type_id
for type_id in self._global_symbols.get(type_name, ())
@@ -1149,6 +1220,29 @@ class ReceiverTypingMixin:
]
return found[0] if len(found) == 1 else None
+ def _python_returned_class(self, symbol: Symbol, path: str) -> str | None:
+ """The class id *symbol*'s return annotation names, read in *path*.
+
+ One bare class name, quoted or not: ``Optional[T]``, ``T | None`` and
+ a qualified name type nothing.
+ """
+ raw = declared_return_type(symbol.signature or "")
+ written = raw.strip("\"' ") if raw else ""
+ found = self._class_named(path, written) if written.isidentifier() else None
+ return None if found is None else found[1]
+
+ def _property_type_id(self, class_file: str, class_id: str, name: str) -> str | None:
+ """The class a Python ``@property`` getter *class_id* declares returns.
+
+ The getter, not its setter, which shares the id and returns nothing.
+ """
+ sym_id = self._declares(class_id, name)
+ parsed = self._parsed_files.get(class_file)
+ for symbol in parsed.symbols if parsed is not None and sym_id is not None else ():
+ if symbol.id == sym_id and is_property_getter(symbol.decorators):
+ return self._python_returned_class(symbol, class_file)
+ return None
+
def _imported_dir(self, file_path: str, local_name: str) -> str | None:
"""The directory of the repository package *file_path* imports as *local_name*."""
parsed = self._parsed_files.get(file_path)
@@ -1166,18 +1260,16 @@ class ReceiverTypingMixin:
"""``x.m()`` where ``x`` holds the type *type_id*, bound by identity.
A go method may sit in any file of its type's package, so the method
- is looked for across that package, not only the type's own file.
+ is looked for across that package, not only the type's own file. A
+ Python method is the one its class declares.
"""
- type_name = self._symbols_by_id[type_id].name
- package = posixpath.dirname(self._symbol_paths_by_id[type_id])
- found = [
- (path, sym_id)
- for path, sym_id in self._global_methods.get((type_name, call.target_name), ())
- if posixpath.dirname(path) == package
- ]
- if len(found) != 1 or found[0][1] == caller_id:
+ if self._symbols_by_id[type_id].language == "python":
+ return self._python_typed_call(file_path, call, caller_id, type_id)
+ hit = self._package_method(type_id, call.target_name)
+ if hit is None or hit[1] == caller_id:
return None
- method_file, sym_id = found[0]
+ method_file, sym_id = hit
+ package = posixpath.dirname(self._symbol_paths_by_id[type_id])
if method_file == file_path:
tier = "same_file"
elif package == posixpath.dirname(file_path):
@@ -1186,6 +1278,26 @@ class ReceiverTypingMixin:
tier = "import"
return self._body_typed_call(caller_id, sym_id, tier, call.line)
+ def _python_typed_call(
+ self, file_path: str, call: CallSite, caller_id: str, type_id: str
+ ) -> ResolvedCall | None:
+ """``_call_typed_receiver`` for a Python class: no package tier."""
+ hit = self._located(file_path, self._declares(type_id, call.target_name))
+ if hit is None or hit[1] == caller_id:
+ return None
+ return self._body_typed_call(caller_id, hit[1], hit[2], call.line)
+
+ def _package_method(self, type_id: str, method_name: str) -> tuple[str, str] | None:
+ """``(file, method id)`` for the one go method of *type_id* in its package."""
+ type_name = self._symbols_by_id[type_id].name
+ package = posixpath.dirname(self._symbol_paths_by_id[type_id])
+ found = [
+ (path, sym_id)
+ for path, sym_id in self._global_methods.get((type_name, method_name), ())
+ if posixpath.dirname(path) == package
+ ]
+ return found[0] if len(found) == 1 else None
+
def _module_types_in(self, file_path: str, language: str) -> dict[str, str | None]:
"""``{name: type}`` for the declarations one file makes at module scope.
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index ba98f2e6d..b73adf7a1 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -41,7 +41,7 @@ from .call_receiver_typing import (
ReceiverTypingMixin,
_store_capped,
)
-from .decorator_names import decorator_base
+from .decorator_names import is_property_accessor
from .lang_helpers.anonymous_classes import is_anonymous_member
from .language_data import (
get_builtin_methods,
@@ -140,23 +140,11 @@ _NON_CALLABLE_KINDS = frozenset({"property"})
# the bare-name indices; its members still resolve through the method index.
_EXTENSION_KINDS = frozenset({"impl"})
-# A getter and its setter are two declarations under one id, which reads as an
-# overload set and is not one: the name is an attribute, not a callable.
-_PROPERTY_DECORATORS = frozenset({"property", "cached_property"})
-_PROPERTY_ACCESSOR_SUFFIXES = (".setter", ".getter", ".deleter")
-
-
-def _is_property_accessor(sym: Any) -> bool:
- for decorator in getattr(sym, "decorators", ()) or ():
- tail = decorator_base(decorator)
- if tail in _PROPERTY_DECORATORS or tail.endswith(_PROPERTY_ACCESSOR_SUFFIXES):
- return True
- return False
-
-
# Languages admitted to the full return-type chain lane; each is admitted
# explicitly, once measured.
-PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset({"cpp", "csharp", "go", "java"})
+PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset(
+ {"cpp", "csharp", "go", "java", "python"}
+)
# Chain lanes that need a file or import/re-export identity for the head type:
# a repository-global simple type name is not a language binding.
@@ -609,7 +597,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
self._tu_local_ids.add(index_id)
if sym.kind in _NON_CALLABLE_KINDS:
self._non_callable_ids.add(index_id)
- if _is_property_accessor(sym):
+ # A getter and its setter are two declarations under one id, which reads
+ # as an overload set and is not one: the name is an attribute.
+ if is_property_accessor(sym.decorators):
self._property_accessor_ids.add(index_id)
# Same rules as the per-file index, for the global-unique tier.
bodiless_method = sym.is_declaration and sym.parent_name is not None
@@ -1055,9 +1045,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if tabled is not None
else self._chain_inner_callee(file_path, call, inner, caller_id, language)
)
- if language == "go" and inner_callee is not None:
+ if language in ("go", "python") and inner_callee is not None:
# A go method may sit in any file of its type's package, so the
# type is read by identity and the method asked for across it.
+ # Python reads its annotation in the callee's file the same way.
type_id = self._returned_type_id(inner_callee)
hit = (
None
@@ -1067,6 +1058,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if hit is not None:
tier = hit.origin.removeprefix("receiver_typed_")
return True, self._return_typed_call(caller_id, hit.callee_id, tier, call.line)
+ if language == "python":
+ # A type name read in the caller's file is not evidence, and an
+ # inherited method is not a refusal: the bare name keeps the site.
+ return False, None
type_name = (
tabled
if tabled is not None
diff --git a/packages/core/src/repowise/core/ingestion/decorator_names.py b/packages/core/src/repowise/core/ingestion/decorator_names.py
index 56437611b..3ee55cd9d 100644
--- a/packages/core/src/repowise/core/ingestion/decorator_names.py
+++ b/packages/core/src/repowise/core/ingestion/decorator_names.py
@@ -2,6 +2,12 @@
from __future__ import annotations
+from collections.abc import Iterable
+
+# Python decorators that make a function an attribute read, not a call.
+PROPERTY_DECORATORS = frozenset({"property", "cached_property"})
+_PROPERTY_ACCESSOR_SUFFIXES = (".setter", ".getter", ".deleter")
+
def decorator_base(raw: str) -> str:
"""``@app.route("/x")`` -> ``app.route``; ``"Deprecated\n public"`` -> ``Deprecated``.
@@ -17,3 +23,15 @@ def decorator_base(raw: str) -> str:
return base[:paren].strip()
parts = base.split()
return parts[0] if parts else base
+
+
+def is_property_getter(decorators: Iterable[str]) -> bool:
+ """A ``@property`` or ``@cached_property`` getter, qualified or not."""
+ return any(decorator_base(d).rpartition(".")[2] in PROPERTY_DECORATORS for d in decorators)
+
+
+def is_property_accessor(decorators: Iterable[str]) -> bool:
+ """A property getter, or a ``@name.setter`` / ``.getter`` / ``.deleter`` beside it."""
+ return is_property_getter(decorators) or any(
+ decorator_base(d).endswith(_PROPERTY_ACCESSOR_SUFFIXES) for d in decorators
+ )
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index d98383dd4..36d8c403a 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -893,15 +893,29 @@ class CallAssignment(NamedTuple):
name: str
receiver: str | None
target: str
+ # Python ``x = await f()``: an ``async def`` yields its annotation only then.
+ awaited: bool = False
-_CALL_ASSIGNMENT_PATTERNS: dict[str, re.Pattern[str]] = {"go": _GO_CALL_DECL}
+# ``x = f(..)``, ``x = await obj.f(..)``: a plain statement-start assignment
+# that ends its line. The resolver refuses a name the body also binds elsewhere.
+_PY_CALL_ASSIGNMENT = re.compile(
+ r"(?m)^[ \t]*(?P<name>[a-z_]\w*)[ \t]*=[ \t]*(?P<awaited>await[ \t]+)?"
+ r"(?:(?P<receiver>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\.)?(?P<target>[A-Za-z_]\w*)\s*\("
+)
+
+_CALL_ASSIGNMENT_PATTERNS: dict[str, re.Pattern[str]] = {
+ "go": _GO_CALL_DECL,
+ "python": _PY_CALL_ASSIGNMENT,
+}
# Languages whose locals may be typed from a call's declared return type.
CALL_TYPED_LANGUAGES = frozenset(_CALL_ASSIGNMENT_PATTERNS)
_QUOTES = frozenset("\"'`")
_STATEMENT_ENDS = frozenset("\n;}")
+# A Python ``;`` may rebind the name later on the line, where no scan sees it.
+_LANGUAGE_STATEMENT_ENDS = {"python": frozenset("\n")}
def _call_end(text: str, index: int) -> int:
@@ -935,11 +949,12 @@ def scan_call_assignments(text: str, language: str) -> tuple[CallAssignment, ...
return ()
cleaned = _without_comments(text, language)
starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ ends = _LANGUAGE_STATEMENT_ENDS.get(language, _STATEMENT_ENDS)
found: list[CallAssignment] = []
for match in pattern.finditer(cleaned):
end = _call_end(cleaned, match.end())
rest = cleaned[end:].lstrip(" \t") if end >= 0 else ""
- if end < 0 or (rest and rest[0] not in _STATEMENT_ENDS):
+ if end < 0 or (rest and rest[0] not in ends):
continue
found.append(
CallAssignment(
@@ -947,6 +962,7 @@ def scan_call_assignments(text: str, language: str) -> tuple[CallAssignment, ...
match.group("name"),
match.group("receiver"),
match.group("target"),
+ bool(match.groupdict().get("awaited")),
)
)
return tuple(found)
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index d4c7b64bd..3330e9f11 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -210,6 +210,19 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
(child for child in function.named_children if child.type == "identifier"), None
)
receiver = None
+ elif function.type == "attribute":
+ # Python ``obj.m()``: the receiver is kept as a plain dotted path,
+ # and a call on anything else is not carried at all.
+ target = function.child_by_field_name("attribute")
+ obj = function.child_by_field_name("object")
+ path = (
+ _receiver_text("python", obj, src)
+ if obj is not None and obj.type in ("identifier", "attribute")
+ else None
+ )
+ if target is None or path is None:
+ return None
+ return CallReceiver(_node_text(target, src).strip(), path, argument_count)
else:
target = (
function.child_by_field_name("name")
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 380a97b0e..2ecc57f0f 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -81,6 +81,8 @@ STORE_FORMAT_VERSION: int = 2
#: update re-keys those symbols and graph nodes. A Swift ``extension`` is an
#: ``impl``, no longer a ``class``. Swift parses with tree-sitter-swift 0.7, so
#: a type body holding ``#if`` keeps its members.
+#: A Python call chained on a method call (``a.get().close()``) carries that
+#: inner call.
PARSER_SCHEMA_VERSION: int = 8
#: state.json key holding the store format version that wrote the store.
diff --git a/tests/unit/ingestion/test_chained_receiver_calls.py b/tests/unit/ingestion/test_chained_receiver_calls.py
index a2d8bd6d9..57ac3c6a2 100644
--- a/tests/unit/ingestion/test_chained_receiver_calls.py
+++ b/tests/unit/ingestion/test_chained_receiver_calls.py
@@ -12,7 +12,7 @@ from datetime import datetime
from pathlib import Path
from repowise.core.ingestion.call_resolver import CallResolver
-from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.models import CallReceiver, FileInfo, ParsedFile
from repowise.core.ingestion.parser import parse_file
@@ -429,6 +429,145 @@ class TestPyChainedFieldCalls:
assert [(c.receiver_name, c.target_name) for c in parsed["m.py"].calls] == [(None, "make")]
+# --- py_property_and_returned_receivers ---------------------------------------
+
+
+def _py_returned(store: str, app: str) -> dict[str, tuple[str, str]]:
+ return {
+ "pkg/users.py": (
+ "python",
+ "class Users:\n def get(self, slug):\n return slug\n",
+ ),
+ "pkg/store.py": ("python", "from pkg.users import Users\n\n" + store),
+ "pkg/app.py": ("python", "from pkg.store import Store\n\n" + app),
+ }
+
+
+_PY_GET = ("pkg/app.py::run", "pkg/users.py::Users::get")
+
+
+def _typed(edges: list[tuple[str, str, float, str]]) -> set[tuple[str, str, str]]:
+ """Edges into ``Users.get`` a receiver type proved, bare-name guesses left out."""
+ prefixes = ("receiver_chain_", "receiver_typed_", "return_type_")
+ return {
+ (e[0], e[1], e[3]) for e in edges if e[1] == _PY_GET[1] and e[3].startswith(prefixes)
+ }
+
+
+class TestPyPropertyAndReturnedReceivers:
+ def test_a_property_getter_annotation_types_the_hop(self, tmp_path: Path) -> None:
+ store = (
+ "class Store:\n"
+ " @property\n"
+ " def users(self) -> Users:\n"
+ " return Users()\n\n"
+ " @users.setter\n"
+ " def users(self, value):\n"
+ " pass\n"
+ )
+ app = "def run(store: Store):\n return store.users.get('x')\n"
+ edges = _edges(tmp_path, _py_returned(store, app), _PY_LINKS)
+ assert (*_PY_GET, "receiver_chain_import") in _typed(edges)
+
+ def test_a_cached_property_types_the_hop(self, tmp_path: Path) -> None:
+ store = (
+ "import functools\n\n"
+ "class Store:\n"
+ " @functools.cached_property\n"
+ " def users(self) -> 'Users':\n"
+ " return Users()\n"
+ )
+ app = "def run(store: Store):\n return store.users.get('x')\n"
+ edges = _edges(tmp_path, _py_returned(store, app), _PY_LINKS)
+ assert (*_PY_GET, "receiver_chain_import") in _typed(edges)
+
+ def test_an_unannotated_or_optional_property_types_nothing(self, tmp_path: Path) -> None:
+ for annotation in ("", " -> Optional[Users]", " -> Users | None"):
+ store = (
+ "class Store:\n"
+ " @property\n"
+ f" def users(self){annotation}:\n"
+ " return Users()\n"
+ )
+ app = "def run(store: Store):\n return store.users.get('x')\n"
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+
+ def test_a_plain_method_is_not_a_property(self, tmp_path: Path) -> None:
+ store = "class Store:\n def users(self) -> Users:\n return Users()\n"
+ app = "def run(store: Store):\n return store.users.get('x')\n"
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+
+ def test_an_assigned_call_types_the_local(self, tmp_path: Path) -> None:
+ store = "class Store:\n def lookup(self) -> Users:\n return Users()\n"
+ for value in ("store.lookup()", "await store.lookup()"):
+ app = f"async def run(store: Store):\n u = {value}\n return u.get('x')\n"
+ edges = _edges(tmp_path, _py_returned(store, app), _PY_LINKS)
+ assert (*_PY_GET, "receiver_typed_import") in _typed(edges)
+
+ def test_a_chained_call_types_the_outer_receiver(self, tmp_path: Path) -> None:
+ store = "class Store:\n def lookup(self) -> Users:\n return Users()\n"
+ app = "def run(store: Store):\n return store.lookup().get('x')\n"
+ edges = _edges(tmp_path, _py_returned(store, app), _PY_LINKS)
+ assert (*_PY_GET, "return_type_import") in _typed(edges)
+
+ def test_an_unannotated_return_types_nothing(self, tmp_path: Path) -> None:
+ store = "class Store:\n def lookup(self):\n return Users()\n"
+ app = (
+ "def run(store: Store):\n"
+ " u = store.lookup()\n"
+ " u.get('x')\n"
+ " return store.lookup().get('y')\n"
+ )
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+
+ def test_a_rebound_local_types_nothing(self, tmp_path: Path) -> None:
+ store = (
+ "class Store:\n"
+ " def lookup(self) -> Users:\n"
+ " return Users()\n\n"
+ " def other(self):\n"
+ " return None\n"
+ )
+ for rebind in ("u = None", "u = store.other()", "for u in []: pass"):
+ app = (
+ "def run(store: Store):\n"
+ " u = store.lookup()\n"
+ f" {rebind}\n"
+ " return u.get('x')\n"
+ )
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+ same_line = "def run(store: Store):\n u = store.lookup(); u = 3\n return u.get('x')\n"
+ assert not _typed(_edges(tmp_path, _py_returned(store, same_line), _PY_LINKS))
+
+ def test_an_async_def_types_only_an_awaited_call(self, tmp_path: Path) -> None:
+ store = "class Store:\n async def lookup(self) -> Users:\n return Users()\n"
+ awaited = "async def run(store: Store):\n u = await store.lookup()\n u.get('x')\n"
+ edges = _edges(tmp_path, _py_returned(store, awaited), _PY_LINKS)
+ assert (*_PY_GET, "receiver_typed_import") in _typed(edges)
+ for app in (
+ "async def run(store: Store):\n u = store.lookup()\n u.get('x')\n",
+ "async def run(store: Store):\n store.lookup().get('x')\n",
+ ):
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+
+ def test_a_property_called_as_a_method_types_nothing(self, tmp_path: Path) -> None:
+ store = (
+ "class Store:\n @property\n def users(self) -> Users:\n return Users()\n"
+ )
+ for app in (
+ "def run(store: Store):\n return store.users().get('x')\n",
+ "def run(store: Store):\n u = store.users()\n return u.get('x')\n",
+ ):
+ assert not _typed(_edges(tmp_path, _py_returned(store, app), _PY_LINKS))
+
+ def test_an_inner_call_keeps_only_a_dotted_receiver(self, tmp_path: Path) -> None:
+ source = "def run(items):\n self.client.get(1).close()\n items[0].get(2).close()\n"
+ parsed = _parse_all(tmp_path, {"m.py": ("python", source)})
+ receivers = {c.line: c.receiver_call for c in parsed["m.py"].calls if c.target_name == "close"}
+ assert receivers[2] == CallReceiver("get", "self.client", 1)
+ assert receivers[3] is None
+
+
# --- go_chained_field_calls --------------------------------------------------
_GO_COMMAND = (
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index 1bd605a3a..eb47e0430 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -775,6 +775,25 @@ class TestGoCallAssignments:
assert scan_call_assignments("x := f()\n", "java") == ()
+class TestPythonCallAssignments:
+ """``x = f(..)``: a whole-statement call, awaited or not."""
+
+ def test_a_dotted_call_and_an_awaited_one(self) -> None:
+ body = "def f():\n r = self.client.get(\n ')'\n )\n s = await g()\n"
+ assert scan_call_assignments(body, "python") == (
+ CallAssignment(2, "r", "self.client", "get"),
+ CallAssignment(5, "s", None, "g", awaited=True),
+ )
+
+ def test_a_comparison_a_chain_and_a_target_list_are_refused(self) -> None:
+ body = "def f():\n x == g()\n y = g().h()\n a, b = g()\n c = g() or d\n"
+ assert scan_call_assignments(body, "python") == ()
+
+ def test_a_statement_after_a_semicolon_is_refused(self) -> None:
+ """``u = f(); u = 3`` rebinds where no binding scan looks."""
+ assert scan_call_assignments("def f():\n u = g(); u = 3\n", "python") == ()
+
+
class TestClassScope:
"""What counts as a field, given that a class span contains every method.
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index b782453a2..c07ebd841 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -215,7 +215,7 @@ def test_unbound_global_return_type_preserves_legacy_fallback(
def test_only_audited_lanes_are_enabled_by_default() -> None:
- assert frozenset({"cpp", "csharp", "go", "java"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
+ assert frozenset({"cpp", "csharp", "go", "java", "python"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
def test_module_level_chain_keeps_structural_receiver(tmp_path: Path) -> None: