Skip to content

Commit 3433449

Browse files
authored
[ty] Reuse full call diagnostics for implicit setter calls (#27115)
## Summary Reuse the full call-error diagnostic machinery for implicit descriptor `__set__` and custom `__setattr__` calls. The call reporter can override the main lint/message, retain the original call failure on the primary annotation, map synthesized arguments back to their source ranges, and add an info diagnostic explaining why the method was called. This PR also correctly re-classifies failed `__setattr__` assignments as `invalid-assignment` instead of `unresolved-attribute`. This PR currently only applies this system to `__set__` and `__setattr__` calls, but it can be extended to any diagnostic resulting from a failed implicit dunder call. Closes astral-sh/ty#4034 ## Test plan Added and updated mdtests covering invalid descriptor values, malformed `__set__` signatures, concise expected/found output, nested tuple incompatibilities, overloaded `__setattr__`, invalid attribute names and values reported together, and instance/metaclass `__setattr__` assignments.
1 parent 2240070 commit 3433449

9 files changed

Lines changed: 543 additions & 133 deletions

File tree

‎crates/ty_python_semantic/resources/mdtest/attributes.md‎

Lines changed: 124 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2980,6 +2980,75 @@ instance.callback = lambda number: (
29802980
instance.payload = {"value": 1}
29812981
```
29822982

2983+
### Nested argument type
2984+
2985+
```py
2986+
class C:
2987+
def __setattr__(self, name: str, value: tuple[int, str]): ...
2988+
2989+
c = C()
2990+
c.x = (1, b"") # snapshot: invalid-assignment
2991+
```
2992+
2993+
```snapshot
2994+
error[invalid-assignment]: Cannot assign object of type `tuple[Literal[1], Literal[b""]]` to attribute `x` on type `C`
2995+
--> src/mdtest_snippet.py:5:7
2996+
|
2997+
5 | c.x = (1, b"") # snapshot: invalid-assignment
2998+
| ^^^^^^^^ Expected `tuple[int, str]`, found `tuple[Literal[1], Literal[b""]]`
2999+
|
3000+
info: This assignment implicitly calls a custom `__setattr__` method
3001+
info: the second tuple element is not compatible: `Literal[b""]` is not assignable to `str`
3002+
info: Method defined here
3003+
--> src/mdtest_snippet.py:2:9
3004+
|
3005+
2 | def __setattr__(self, name: str, value: tuple[int, str]): ...
3006+
| ^^^^^^^^^^^ ---------------------- Parameter declared here
3007+
|
3008+
```
3009+
3010+
### Overloaded `__setattr__`
3011+
3012+
```py
3013+
from typing import overload
3014+
3015+
class D:
3016+
@overload
3017+
def __setattr__(self, name: str, value: tuple[int, str]): ...
3018+
@overload
3019+
def __setattr__(self, name: str, value: int): ...
3020+
def __setattr__(self, name: str, value: tuple[int, str] | int): ...
3021+
3022+
d = D()
3023+
d.x = (1, b"") # snapshot: invalid-assignment
3024+
```
3025+
3026+
```snapshot
3027+
error[invalid-assignment]: Cannot assign object of type `tuple[Literal[1], Literal[b""]]` to attribute `x` on type `D`
3028+
--> src/mdtest_snippet.py:11:1
3029+
|
3030+
11 | d.x = (1, b"") # snapshot: invalid-assignment
3031+
| ^^^ No overload of bound method `D.__setattr__` matches arguments
3032+
|
3033+
info: This assignment implicitly calls a custom `__setattr__` method
3034+
info: First overload defined here
3035+
--> src/mdtest_snippet.py:4:5
3036+
|
3037+
4 | / @overload
3038+
5 | | def __setattr__(self, name: str, value: tuple[int, str]): ...
3039+
| |_________________________________________________________________^ First overload defined here
3040+
|
3041+
info: Possible overloads for bound method `__setattr__`:
3042+
info: (self, name: str, value: tuple[int, str]) -> Unknown
3043+
info: (self, name: str, value: int) -> Unknown
3044+
info: Overload implementation defined here
3045+
--> src/mdtest_snippet.py:8:9
3046+
|
3047+
8 | def __setattr__(self, name: str, value: tuple[int, str] | int): ...
3048+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3049+
|
3050+
```
3051+
29833052
### Type of the `name` parameter
29843053

29853054
If the `name` parameter of the `__setattr__` method is annotated with a (union of) literal type(s),
@@ -2998,10 +3067,58 @@ date.day = 8
29983067
date.month = 4
29993068
date.year = 2025
30003069

3001-
# error: [unresolved-attribute] "Cannot assign object of type `Literal["UTC"]` to attribute `tz` on type `Date` with custom `__setattr__` method."
3070+
date.month = "May" # snapshot: invalid-assignment
3071+
# snapshot: invalid-assignment
3072+
# snapshot: invalid-assignment
30023073
date.tz = "UTC"
30033074
```
30043075

3076+
```snapshot
3077+
error[invalid-assignment]: Cannot assign object of type `Literal["May"]` to attribute `month` on type `Date`
3078+
--> src/mdtest_snippet.py:13:14
3079+
|
3080+
13 | date.month = "May" # snapshot: invalid-assignment
3081+
| ^^^^^ Expected `int`, found `Literal["May"]`
3082+
|
3083+
info: This assignment implicitly calls a custom `__setattr__` method
3084+
info: Method defined here
3085+
--> src/mdtest_snippet.py:5:9
3086+
|
3087+
5 | def __setattr__(self, name: Literal["day", "month", "year"], value: int) -> None:
3088+
| ^^^^^^^^^^^ ---------- Parameter declared here
3089+
|
3090+
3091+
3092+
error[invalid-assignment]: Cannot assign object of type `Literal["UTC"]` to attribute `tz` on type `Date`
3093+
--> src/mdtest_snippet.py:16:1
3094+
|
3095+
16 | date.tz = "UTC"
3096+
| ^^^^^^^ Expected `Literal["day", "month", "year"]`, found `Literal["tz"]`
3097+
|
3098+
info: This assignment implicitly calls a custom `__setattr__` method
3099+
info: Method defined here
3100+
--> src/mdtest_snippet.py:5:9
3101+
|
3102+
5 | def __setattr__(self, name: Literal["day", "month", "year"], value: int) -> None:
3103+
| ^^^^^^^^^^^ ------------------------------------- Parameter declared here
3104+
|
3105+
3106+
3107+
error[invalid-assignment]: Cannot assign object of type `Literal["UTC"]` to attribute `tz` on type `Date`
3108+
--> src/mdtest_snippet.py:16:11
3109+
|
3110+
16 | date.tz = "UTC"
3111+
| ^^^^^ Expected `int`, found `Literal["UTC"]`
3112+
|
3113+
info: This assignment implicitly calls a custom `__setattr__` method
3114+
info: Method defined here
3115+
--> src/mdtest_snippet.py:5:9
3116+
|
3117+
5 | def __setattr__(self, name: Literal["day", "month", "year"], value: int) -> None:
3118+
| ^^^^^^^^^^^ ---------- Parameter declared here
3119+
|
3120+
```
3121+
30053122
### Return type of `__setattr__`
30063123

30073124
If the return type of the `__setattr__` method is `Never`, we do not allow any attribute assignments
@@ -3117,7 +3234,7 @@ def use_module(m: MyModule, param: int) -> None:
31173234

31183235
# But assigning to an attribute that's not explicitly defined will still
31193236
# use `__setattr__` for validation.
3120-
# error: [unresolved-attribute] "Cannot assign object of type `int` to attribute `undefined_param` on type `MyModule` with custom `__setattr__` method."
3237+
# error: [invalid-assignment] "Cannot assign object of type `int` to attribute `undefined_param` on type `MyModule`"
31213238
m.undefined_param = param
31223239
```
31233240

@@ -3158,7 +3275,7 @@ class Meta(type):
31583275
class Foo(metaclass=Meta): ...
31593276

31603277
Foo.whatever = 42
3161-
Foo.whatever = "invalid" # error: [unresolved-attribute] "with custom `__setattr__` method"
3278+
Foo.whatever = "invalid" # error: [invalid-assignment]
31623279
```
31633280

31643281
If both the metaclass and class define `__setattr__`, class-object assignments use the metaclass
@@ -3169,19 +3286,19 @@ class WithSetAttr(metaclass=Meta):
31693286
def __setattr__(self, name: str, value: str) -> None: ...
31703287

31713288
WithSetAttr.class_attribute = 42
3172-
WithSetAttr.class_attribute = "invalid" # error: [unresolved-attribute] "with custom `__setattr__` method"
3289+
WithSetAttr.class_attribute = "invalid" # error: [invalid-assignment]
31733290

31743291
instance = WithSetAttr()
31753292
instance.instance_attribute = "valid"
3176-
instance.instance_attribute = 42 # error: [unresolved-attribute] "with custom `__setattr__` method"
3293+
instance.instance_attribute = 42 # error: [invalid-assignment]
31773294
```
31783295

31793296
The same applies when the class object is annotated as `type[Foo]`:
31803297

31813298
```py
31823299
def set_on_subclass(cls: type[Foo]) -> None:
31833300
cls.whatever = 42
3184-
cls.whatever = "invalid" # error: [unresolved-attribute] "with custom `__setattr__` method"
3301+
cls.whatever = "invalid" # error: [invalid-assignment]
31853302
```
31863303

31873304
The setter also provides the expected type when inferring the assigned value:
@@ -3225,7 +3342,7 @@ OverloadedClass.callback = lambda number: (
32253342
number.missing
32263343
)
32273344
OverloadedClass.payload = {"value": 1}
3228-
OverloadedClass.callback = {"value": 1} # error: [unresolved-attribute] "with custom `__setattr__` method"
3345+
OverloadedClass.callback = {"value": 1} # error: [invalid-assignment]
32293346
```
32303347

32313348
A metaclass `__setattr__` method returning `Never` prevents writes to undefined attributes:

‎crates/ty_python_semantic/resources/mdtest/descriptor_protocol.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ reveal_type(C.ten) # revealed: Literal[10]
3535
# This is fine:
3636
c.ten = 10
3737

38-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `ten` on type `C` with custom `__set__` method"
38+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `ten` on type `C`"
3939
c.ten = 11
4040
```
4141

@@ -78,7 +78,7 @@ c.flexible_int = "42" # also okay!
7878

7979
reveal_type(c.flexible_int) # revealed: int | None
8080

81-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `flexible_int` on type `C` with custom `__set__` method"
81+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `flexible_int` on type `C`"
8282
c.flexible_int = None # not okay
8383

8484
reveal_type(c.flexible_int) # revealed: int | None
@@ -215,7 +215,7 @@ def f1(flag: bool):
215215
attr = DataDescriptor()
216216

217217
def f(self):
218-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `attr` on type `Self@f` with custom `__set__` method"
218+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `attr` on type `Self@f`"
219219
self.attr = b"foo"
220220

221221
reveal_type(C1().attr) # revealed: Literal["data"] | bytes
@@ -480,7 +480,7 @@ on the metaclass:
480480
```py
481481
C1.meta_data_descriptor = 1
482482

483-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `meta_data_descriptor` on type `<class 'C1'>` with custom `__set__` method"
483+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `meta_data_descriptor` on type `<class 'C1'>`"
484484
C1.meta_data_descriptor = "invalid"
485485
```
486486

@@ -586,7 +586,7 @@ def _(flag: bool):
586586
# TODO: We currently emit two diagnostics here, corresponding to the two states of `flag`. The diagnostics are not
587587
# wrong, but they could be subsumed under a higher-level diagnostic.
588588

589-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `meta_data_descriptor1` on type `<class 'C5'>` with custom `__set__` method"
589+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `meta_data_descriptor1` on type `<class 'C5'>`"
590590
# error: [invalid-assignment] "Object of type `None` is not assignable to attribute `meta_data_descriptor1` of type `Literal["value on class"]`"
591591
C5.meta_data_descriptor1 = None
592592

@@ -735,7 +735,7 @@ reveal_type(C.name) # revealed: property
735735
c.name = "new"
736736
c.name = None
737737

738-
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `name` on type `C` with custom `__set__` method"
738+
# error: [invalid-assignment] "Invalid assignment to data descriptor attribute `name` on type `C`"
739739
c.name = 42
740740
```
741741

‎crates/ty_python_semantic/resources/mdtest/diagnostics/attribute_assignment.md‎

Lines changed: 92 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -274,17 +274,27 @@ class C:
274274
instance = C()
275275
instance.attr = 1 # fine
276276

277-
# TODO: ideally, we would mention why this is an invalid assignment (wrong argument type for `value` parameter)
278277
instance.attr = "wrong" # snapshot: invalid-assignment
278+
279+
# Check that the concise diagnostic retains the useful expected and provided types.
280+
# error: [invalid-assignment] "Expected `int`, found `Literal["also wrong"]`"
281+
instance.attr = "also wrong"
279282
```
280283

281284
```snapshot
282-
error[invalid-assignment]: Invalid assignment to data descriptor attribute `attr` on type `C` with custom `__set__` method
283-
--> src/mdtest_snippet.py:12:1
285+
error[invalid-assignment]: Invalid assignment to data descriptor attribute `attr` on type `C`
286+
--> src/mdtest_snippet.py:11:17
284287
|
285-
12 | instance.attr = "wrong" # snapshot: invalid-assignment
286-
| ^^^^^^^^^^^^^
288+
11 | instance.attr = "wrong" # snapshot: invalid-assignment
289+
| ^^^^^^^ Expected `int`, found `Literal["wrong"]`
287290
|
291+
info: This assignment implicitly calls `__set__` on a descriptor of type `Descriptor`
292+
info: Function defined here
293+
--> src/mdtest_snippet.py:2:9
294+
|
295+
2 | def __set__(self, instance: object, value: int) -> None:
296+
| ^^^^^^^ ---------- Parameter declared here
297+
|
288298
```
289299

290300
### Invalid `__set__` method signature
@@ -299,17 +309,89 @@ class C:
299309

300310
instance = C()
301311

302-
# TODO: ideally, we would mention why this is an invalid assignment (wrong number of arguments for `__set__`)
303312
instance.attr = 1 # snapshot: invalid-assignment
304313
```
305314

306315
```snapshot
307-
error[invalid-assignment]: Invalid assignment to data descriptor attribute `attr` on type `C` with custom `__set__` method
308-
--> src/mdtest_snippet.py:11:1
316+
error[invalid-assignment]: Invalid assignment to data descriptor attribute `attr` on type `C`
317+
--> src/mdtest_snippet.py:10:1
318+
|
319+
10 | instance.attr = 1 # snapshot: invalid-assignment
320+
| ^^^^^^^^^^^^^ No argument provided for required parameter `extra` of function `WrongDescriptor.__set__`
321+
|
322+
info: This assignment implicitly calls `__set__` on a descriptor of type `WrongDescriptor`
323+
info: Parameter declared here
324+
--> src/mdtest_snippet.py:2:53
325+
|
326+
2 | def __set__(self, instance: object, value: int, extra: int) -> None:
327+
| ^^^^^^^^^^
328+
|
329+
```
330+
331+
### Invalid property setter argument type
332+
333+
```py
334+
class Document: ...
335+
336+
class HasDocumentRef:
337+
@property
338+
def document(self) -> Document | None: ...
339+
@document.setter
340+
def document(self, document: Document) -> None: ...
341+
342+
class Model(HasDocumentRef):
343+
def detach(self) -> None:
344+
self.document = None # snapshot: invalid-assignment
345+
346+
# Check that the concise diagnostic identifies the actual setter argument mismatch.
347+
# error: [invalid-assignment] "Expected `Document`, found `None`"
348+
self.document = None
349+
```
350+
351+
```snapshot
352+
error[invalid-assignment]: Invalid assignment to data descriptor attribute `document` on type `Self@detach`
353+
--> src/mdtest_snippet.py:11:25
309354
|
310-
11 | instance.attr = 1 # snapshot: invalid-assignment
311-
| ^^^^^^^^^^^^^
355+
11 | self.document = None # snapshot: invalid-assignment
356+
| ^^^^ Expected `Document`, found `None`
312357
|
358+
info: This assignment implicitly calls `__set__` on a descriptor of type `property`
359+
info: Function defined here
360+
--> src/mdtest_snippet.py:7:9
361+
|
362+
7 | def document(self, document: Document) -> None: ...
363+
| ^^^^^^^^ ------------------ Parameter declared here
364+
|
365+
```
366+
367+
### Nested argument type
368+
369+
```py
370+
class Descriptor:
371+
def __set__(self, instance, value: tuple[int, str]) -> None: ...
372+
373+
class C:
374+
x = Descriptor()
375+
376+
c = C()
377+
c.x = (1, b"") # snapshot: invalid-assignment
378+
```
379+
380+
```snapshot
381+
error[invalid-assignment]: Invalid assignment to data descriptor attribute `x` on type `C`
382+
--> src/mdtest_snippet.py:8:7
383+
|
384+
8 | c.x = (1, b"") # snapshot: invalid-assignment
385+
| ^^^^^^^^ Expected `tuple[int, str]`, found `tuple[Literal[1], Literal[b""]]`
386+
|
387+
info: This assignment implicitly calls `__set__` on a descriptor of type `Descriptor`
388+
info: the second tuple element is not compatible: `Literal[b""]` is not assignable to `str`
389+
info: Function defined here
390+
--> src/mdtest_snippet.py:2:9
391+
|
392+
2 | def __set__(self, instance, value: tuple[int, str]) -> None: ...
393+
| ^^^^^^^ ---------------------- Parameter declared here
394+
|
313395
```
314396

315397
## Setting attributes on union types

0 commit comments

Comments
 (0)