Files
David Peter 324bcac22e [ty] Support shadowing methods on instances (#29482)
## Summary

With this PR, we now support the following scenario where a function on
a class is shadowed by an instance attribute:

```python
class C:
    def method(self, x: int) -> str:
        return str(x)

    def some_compatible_method(self, x: int) -> str:
        return str(x)

    def swap(self) -> None:
        self.method = self.some_compatible_method  # previously an error

c = C()
c.swap()
c.method(42)  # previously an error (two, actually)
```

(see [this
section](https://github.com/astral-sh/ruff/blob/078b001e5c09f9c301ee7d91092b4946d0591d63/crates/ty_python_semantic/resources/mdtest/call/methods.md#shadowing-methods)
for an in-depth description of what happens here)

Shadowing a method in this way is only sound in a small number of cases.
We deliberately relax conditions here to support various use cases that
came up in the ecosystem. We only require the shadowing callable
(`self.some_compatible_method` above) to be assignable to the
(generalized, regular) callable type of the original `method` after that
has been bound to the receiver in question (`self` here).

See the mdtests linked above for a broaded discussion of the unsoundness
that this introduces. We plan to add a new strict-mode diagnostic for
users who want to prevent those scenarios.

We implement this in the following way:
- When validating the assignment `self.method = ...`, we compare the
right-hand side callable with a "contract type" that is computed from
the bound-method type of the original method, which results in (`(x:
int) -> str`) for the example above. This allows the assignment above to
pass.
- During attribute lookup (`c.method`), we "hide" the implicit instance
attribute (this needs to be done in two places, unfortunately). This
means that `c.method` only sees the original function on the meta type
`C` (and no "fallback" on the instance). And so according to normal
descriptor protocol rules, this means that we simply get a bound method
object (`C.method` bound to `c`). This avoids confusing and problematic
union types that consist of (a) the bound method resulting from binding
the original function to the new receiver and (b) the bound method
referring to the `self` receiver which is stored on the instance. It
might also be a performance optimization.

fixes astral-sh/ty#350.
fixes astral-sh/ty#4823.

## Ecosystem

Looks good. A few exceptions:

- GraphQL-core: I documented this regression in an mdtest. See my inline
comment
- hydra-zen: This is a pre-existing limitation. I reported
https://github.com/astral-sh/ty/issues/4926

## Testing

Updated existing mdtests
2026-11-05 15:31:31 +01:00

1.7 KiB

Shadowing

We currently show special diagnostic hints when a class or function is shadowed by a variable assignment.

Implicit class shadowing

class C: ...

C = 1  # snapshot: invalid-assignment
error[invalid-assignment]: Object of type `Literal[1]` is not assignable to `<class 'C'>`
 --> src/mdtest_snippet.py:3:5
  |
3 | C = 1  # snapshot: invalid-assignment
  | -   ^ Incompatible value of type `Literal[1]`
  | |
  | Declared type `<class 'C'>`
info: Implicit shadowing of class `C`. Add an annotation to make it explicit if this is intentional

Implicit function shadowing

def f(): ...

f = 1  # snapshot: invalid-assignment
error[invalid-assignment]: Object of type `Literal[1]` is not assignable to `def f() -> Unknown`
 --> src/mdtest_snippet.py:3:5
  |
3 | f = 1  # snapshot: invalid-assignment
  | -   ^ Incompatible value of type `Literal[1]`
  | |
  | Declared type `def f() -> Unknown`
info: Implicit shadowing of function `f`. Add an annotation to make it explicit if this is intentional

No implicit shadowing for attribute assignments

from configparser import ConfigParser

config = ConfigParser()
config.optionxform = str  # snapshot: invalid-assignment
error[invalid-assignment]: Object of type `<class 'str'>` is not assignable to attribute `optionxform` of type `(optionstr: str) -> str`
 --> src/mdtest_snippet.py:4:1
  |
4 | config.optionxform = str  # snapshot: invalid-assignment
  | ^^^^^^^^^^^^^^^^^^
info: type `<class 'str'>` has inferred callable type `Overload[(object: object = "") -> str, (object: Buffer, encoding: str = "utf-8", errors: str = "strict") -> str]`