Currently some synthesized methods handle `Self` differently than normal
methods: instead of treating `Self` as an inferrable typevar in the
generic context of the synthesized methods, they eagerly replace `Self`
with the concrete defining class.
The code implementing this eager substitution was a little too broad,
and could also catch method aliases, in cases like this (real-world
example):
```py
from collections.abc import Awaitable
from typing import Any, Literal, Protocol, overload, reveal_type
class AsyncClient(Protocol):
_is_async_client: Literal[True]
class SyncClient(Protocol):
_is_async_client: Literal[False]
class Commands:
@overload
def incrby(self: SyncClient, name: str) -> int: ...
@overload
def incrby(self: AsyncClient, name: str) -> Awaitable[int]: ...
def incrby(self: Any, name: str) -> int | Awaitable[int]:
raise NotImplementedError
incr = incrby
class Redis(Commands):
_is_async_client: Literal[True] = True
def f(r: Redis) -> None:
reveal_type(r.incrby("k")) # Awaitable[int]
reveal_type(r.incr("k")) # expected Awaitable[int]
```
On main, we incorrectly categorize the `incr` alias as a synthesized
method, so we prune overloads correctly for `r.incrby` calls but not for
`r.incr` calls.
This PR makes `Self` handling consistent across synthesized and normal
methods, which fixes these calls to method aliases, too.
Synthesized named-tuple and dataclass methods now register `Self` in
their generic contexts and connect field annotations to that inferable
type variable. This lets them use ordinary call inference. Anonymous
decorator results retain a temporary fallback for
[ty#3186](https://github.com/astral-sh/ty/issues/3186) when a receiver
type variable has no generic context. Specialized protocol receivers and
constrained receivers retain their existing handling.
Pydantic constructor receivers are positional-only, matching the runtime
signature and keeping fields named `self` separate from the receiver.
Fixes astral-sh/ty#4715.
## Test plan
Ran the classmethod, constrained-TypedDict, and union-receiver examples
from the review of #26861 against this implementation. Aliased
classmethods preserve their return types and subclass `Self`;
constrained TypedDict subscription is accepted; the invalid
union-receiver call retains `no-matching-overload` diagnostics instead
of becoming non-callable.
## Ecosystem report
Analyzed
[`6052e4fb1c`](https://github.com/astral-sh/ruff/commit/6052e4fb1c6f941ead46f4a103810802dbe14e38).
Most changes update existing receiver counts; alias return inference
improves, and borrowed methods and classmethod aliases enforce their
receiver constraints. Additional diagnostics expose an existing
native-function binding limitation. All public ecosystem changes are
accounted for and do not block this PR. [Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/29341#issuecomment-6157452697).
3.9 KiB
replace
The replace function and the replace protocol were added in Python 3.13:
https://docs.python.org/3/whatsnew/3.13.html#copy
[environment]
python-version = "3.13"
Basic
from copy import replace
from datetime import time
t = time(12, 0, 0)
t = replace(t, minute=30)
reveal_type(t) # revealed: time
The __replace__ protocol
Dataclasses
Dataclasses support the __replace__ protocol:
from dataclasses import dataclass
from copy import replace
@dataclass
class Point:
x: int
y: int
reveal_type(Point.__replace__) # revealed: (self: Point, /, *, x: int = ..., y: int = ...) -> Point
The __replace__ method can either be called directly or through the replace function:
a = Point(1, 2)
b = a.__replace__(x=3, y=4)
reveal_type(b) # revealed: Point
b = replace(a, x=3, y=4)
reveal_type(b) # revealed: Point
A call to replace does not require all keyword arguments:
c = a.__replace__(y=4)
reveal_type(c) # revealed: Point
d = replace(a, y=4)
reveal_type(d) # revealed: Point
Invalid calls to __replace__ or replace will raise an error:
e = a.__replace__(x="wrong") # error: [invalid-argument-type]
# error: [invalid-argument-type] "Argument to function `replace` is incorrect: Expected `int`, found `Literal["wrong"]`"
e = replace(a, x="wrong")
Dataclass fields named self
The receiver of __replace__ is positional-only, so a keyword argument named self replaces the
field:
from dataclasses import dataclass
from copy import replace
@dataclass
class Record:
self: int
record = Record(self=1)
reveal_type(record.__replace__(self=2)) # revealed: Record
reveal_type(replace(record, self=2)) # revealed: Record
record.__replace__(self="wrong") # error: [invalid-argument-type]
replace(record, self="wrong") # error: [invalid-argument-type]
Dataclass transforms
Classes transformed through a base class or metaclass also support the __replace__ protocol.
from copy import replace
from typing import dataclass_transform
@dataclass_transform()
class ModelBase: ...
class BaseModel(ModelBase):
value: int
# revealed: (self: BaseModel, /, *, value: int = ...) -> BaseModel
reveal_type(BaseModel.__replace__)
base_model = BaseModel(value=1)
reveal_type(base_model.__replace__(value=2)) # revealed: BaseModel
reveal_type(replace(base_model, value=2)) # revealed: BaseModel
@dataclass_transform()
class ModelMetaclass(type): ...
class MetaclassModel(metaclass=ModelMetaclass):
value: int
# revealed: (self: MetaclassModel, /, *, value: int = ...) -> MetaclassModel
reveal_type(MetaclassModel.__replace__)
metaclass_model = MetaclassModel(value=1)
reveal_type(metaclass_model.__replace__(value=2)) # revealed: MetaclassModel
reveal_type(replace(metaclass_model, value=2)) # revealed: MetaclassModel
NamedTuples
NamedTuples also support the __replace__ protocol:
from typing import NamedTuple
from copy import replace
class Point(NamedTuple):
x: int
y: int
reveal_type(Point.__replace__) # revealed: [Self](self: Self, /, *, x: int = ..., y: int = ...) -> Self
The __replace__ method can either be called directly or through the replace function:
a = Point(1, 2)
b = a.__replace__(x=3, y=4)
reveal_type(b) # revealed: Point
b = replace(a, x=3, y=4)
reveal_type(b) # revealed: Point
Invalid calls to __replace__ will raise an error:
# error: [unknown-argument] "Argument `z` does not match any known parameter"
a.__replace__(z=42)
Before Python 3.13
Dataclass transforms do not synthesize __replace__ before the replacement protocol exists.
[environment]
python-version = "3.12"
from typing import dataclass_transform
@dataclass_transform()
class ModelBase: ...
class Model(ModelBase):
value: int
Model.__replace__ # error: [missing-attribute]
Model(value=1).__replace__ # error: [missing-attribute]