mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 02:03:58 +08:00
[ty] Explain slots and custom setters in override diagnostics (#29531)
Override diagnostics could claim that an annotated attribute was not writable without explaining that `__slots__` provided no storage for it. Add that context to `incompatible-property-override` and `incompatible-mutable-override` when the attribute has neither a matching slot nor an instance dictionary. When an override relies on a custom `__setattr__` that rejects the inherited write type, point to that setter and explain the missing storage where applicable. Preserve the existing diagnostic when the incompatibility comes from the declared write type or a property setter. Addresses [the diagnostic context requested in ty#4745](https://github.com/astral-sh/ty/issues/4745#issuecomment-6273127394).
This commit is contained in:
@@ -4367,6 +4367,207 @@ class PropertyChild(Base):
|
||||
return ""
|
||||
```
|
||||
|
||||
## Property overrides without instance storage
|
||||
|
||||
When an instance attribute replaces a writable property and no custom `__setattr__` handles writes,
|
||||
the subclass needs a matching slot or an instance dictionary. A matching read type is not
|
||||
sufficient.
|
||||
|
||||
```py
|
||||
class Base:
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def value(self) -> int:
|
||||
return 0
|
||||
|
||||
@value.setter
|
||||
def value(self, value: int) -> None: ...
|
||||
|
||||
class Child(Base):
|
||||
__slots__ = ()
|
||||
value: int # snapshot: incompatible-property-override
|
||||
```
|
||||
|
||||
```snapshot
|
||||
error[incompatible-property-override]: Invalid override of attribute `value`
|
||||
--> src/mdtest_snippet.py:13:5
|
||||
|
|
||||
9 | def value(self, value: int) -> None: ...
|
||||
| ----- `Base.value` declared here
|
||||
10 |
|
||||
11 | class Child(Base):
|
||||
12 | __slots__ = ()
|
||||
13 | value: int # snapshot: incompatible-property-override
|
||||
| ^^^^^ Override does not accept writes of type `int`
|
||||
info: Attribute `value` is not included in `__slots__`, and the class has no instance dictionary
|
||||
```
|
||||
|
||||
## Descriptor overrides without instance storage
|
||||
|
||||
An instance attribute replacing a writable descriptor must preserve its write contract. Without a
|
||||
custom `__setattr__`, that requires a matching slot or an instance dictionary.
|
||||
|
||||
```py
|
||||
class Descriptor:
|
||||
def __get__(self, instance: object, owner: type | None = None) -> int:
|
||||
return 0
|
||||
|
||||
def __set__(self, instance: object, value: int) -> None: ...
|
||||
|
||||
class Base:
|
||||
__slots__ = ()
|
||||
value: Descriptor = Descriptor()
|
||||
|
||||
class Child(Base):
|
||||
__slots__ = ()
|
||||
value: int # snapshot: incompatible-mutable-override
|
||||
```
|
||||
|
||||
```snapshot
|
||||
error[incompatible-mutable-override]: Invalid override of attribute `value`
|
||||
--> src/mdtest_snippet.py:13:5
|
||||
|
|
||||
9 | value: Descriptor = Descriptor()
|
||||
| ----- `Base.value` declared here
|
||||
10 |
|
||||
11 | class Child(Base):
|
||||
12 | __slots__ = ()
|
||||
13 | value: int # snapshot: incompatible-mutable-override
|
||||
| ^^^^^ Override does not accept writes of type `int`
|
||||
info: Attribute `value` is not included in `__slots__`, and the class has no instance dictionary
|
||||
```
|
||||
|
||||
## Slotted property setters with incompatible write types
|
||||
|
||||
A property setter does not require a slot for the property name. Narrowing its accepted type breaks
|
||||
its write contract, even when the subclass has no instance storage for that name.
|
||||
|
||||
```py
|
||||
class Base:
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def value(self) -> int:
|
||||
return 0
|
||||
|
||||
@value.setter
|
||||
def value(self, value: int) -> None: ...
|
||||
|
||||
class Child(Base):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def value(self) -> int:
|
||||
return 0
|
||||
|
||||
@value.setter
|
||||
def value(self, value: bool) -> None: ... # snapshot: incompatible-property-override
|
||||
```
|
||||
|
||||
```snapshot
|
||||
error[incompatible-property-override]: Invalid override of attribute `value`
|
||||
--> src/mdtest_snippet.py:19:9
|
||||
|
|
||||
19 | def value(self, value: bool) -> None: ... # snapshot: incompatible-property-override
|
||||
| ^^^^^ Override does not accept writes of type `int`
|
||||
|
|
||||
::: src/mdtest_snippet.py:9:9
|
||||
|
|
||||
9 | def value(self, value: int) -> None: ...
|
||||
| ----- `Base.value` declared here
|
||||
```
|
||||
|
||||
## Slotted overrides with incompatible declared write types
|
||||
|
||||
A custom `__setattr__` accepting the inherited write type does not make a narrower attribute
|
||||
declaration compatible. The diagnostic does not blame the custom setter for this incompatibility.
|
||||
|
||||
```py
|
||||
class Base:
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def value(self) -> int:
|
||||
return 0
|
||||
|
||||
@value.setter
|
||||
def value(self, value: int) -> None: ...
|
||||
|
||||
class Child(Base):
|
||||
__slots__ = ()
|
||||
value: bool # snapshot: incompatible-property-override
|
||||
|
||||
def __setattr__(self, name: str, value: int) -> None: ...
|
||||
```
|
||||
|
||||
```snapshot
|
||||
error[incompatible-property-override]: Invalid override of attribute `value`
|
||||
--> src/mdtest_snippet.py:13:5
|
||||
|
|
||||
9 | def value(self, value: int) -> None: ...
|
||||
| ----- `Base.value` declared here
|
||||
10 |
|
||||
11 | class Child(Base):
|
||||
12 | __slots__ = ()
|
||||
13 | value: bool # snapshot: incompatible-property-override
|
||||
| ^^^^^ Override does not accept writes of type `int`
|
||||
```
|
||||
|
||||
## Slotted overrides with incompatible `__setattr__`
|
||||
|
||||
Without a matching slot or instance dictionary, the override relies on a custom `__setattr__` to
|
||||
accept writes. If the setter rejects the inherited write type, the diagnostic explains this and
|
||||
points to the setter, including when it is inherited from another module.
|
||||
|
||||
`setters.py`:
|
||||
|
||||
```py
|
||||
class Setter:
|
||||
__slots__ = ()
|
||||
|
||||
def __setattr__(self, name: str, value: bool) -> None: ...
|
||||
```
|
||||
|
||||
`main.py`:
|
||||
|
||||
```py
|
||||
from setters import Setter
|
||||
|
||||
class Base:
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def value(self) -> int:
|
||||
return 0
|
||||
|
||||
@value.setter
|
||||
def value(self, value: int) -> None: ...
|
||||
|
||||
class Child(Base, Setter):
|
||||
__slots__ = ()
|
||||
value: int # snapshot: incompatible-property-override
|
||||
```
|
||||
|
||||
```snapshot
|
||||
error[incompatible-property-override]: Invalid override of attribute `value`
|
||||
--> src/main.py:15:5
|
||||
|
|
||||
11 | def value(self, value: int) -> None: ...
|
||||
| ----- `Base.value` declared here
|
||||
12 |
|
||||
13 | class Child(Base, Setter):
|
||||
14 | __slots__ = ()
|
||||
15 | value: int # snapshot: incompatible-property-override
|
||||
| ^^^^^ Override does not accept writes of type `int`
|
||||
|
|
||||
::: src/setters.py:4:9
|
||||
|
|
||||
4 | def __setattr__(self, name: str, value: bool) -> None: ...
|
||||
| ----------- This `__setattr__` does not accept writes of type `int`
|
||||
info: Attribute `value` is missing from `__slots__` and the class has no instance dictionary, so this override relies on `__setattr__` accepting writes
|
||||
```
|
||||
|
||||
## Attribute contracts inherited from `object`
|
||||
|
||||
Typeshed declares metadata such as `__module__: str` on `object`. Normally, this annotation would
|
||||
|
||||
@@ -79,6 +79,55 @@ pub(super) enum AttributeWriteRequirement<'db> {
|
||||
},
|
||||
}
|
||||
|
||||
impl<'db> AttributeWriteRequirement<'db> {
|
||||
/// Explain a failed write that falls back to `__setattr__`.
|
||||
/// Callers must first check that the write actually fails, since a custom setter can accept it.
|
||||
pub(super) fn failure_reason(
|
||||
&self,
|
||||
db: &'db dyn Db,
|
||||
env: &ProgramEnvironment<'db>,
|
||||
attribute: &str,
|
||||
) -> Option<AttributeWriteFailure<'db>> {
|
||||
let Self::Instance {
|
||||
object_ty,
|
||||
receiver,
|
||||
member: InstanceAttributeWriteMember::SetAttr,
|
||||
} = self
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let missing_slot = object_ty
|
||||
.nominal_class(db, env)
|
||||
.and_then(|class| class.static_class_literal(db))
|
||||
.is_some_and(|(class, _)| class.lacks_instance_storage(db, attribute));
|
||||
match attribute_setattr_member(
|
||||
db,
|
||||
env,
|
||||
*object_ty,
|
||||
*receiver,
|
||||
instance_setattr_dispatch(db, env, *object_ty, attribute),
|
||||
)
|
||||
.place
|
||||
{
|
||||
Place::Defined(setattr) => Some(AttributeWriteFailure::SetAttr {
|
||||
definition: setattr.provenance.definition(),
|
||||
missing_slot,
|
||||
}),
|
||||
Place::Undefined => missing_slot.then_some(AttributeWriteFailure::MissingSlot),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Context for a failed write when neither a descriptor nor instance storage handles it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum AttributeWriteFailure<'db> {
|
||||
MissingSlot,
|
||||
SetAttr {
|
||||
definition: Option<Definition<'db>>,
|
||||
missing_slot: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// How a writable protocol member validates an assigned value.
|
||||
pub(super) enum ProtocolMemberWriteRequirement<'db> {
|
||||
/// Check the assigned value against a directly representable write type.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
use std::cell::{LazyCell, OnceCell};
|
||||
|
||||
use ruff_db::diagnostic::Annotation;
|
||||
use ruff_db::diagnostic::{Annotation, Span};
|
||||
use ruff_db::parsed::parsed_module;
|
||||
use ruff_python_ast::name::Name;
|
||||
use ruff_python_stdlib::identifiers::is_mangled_private;
|
||||
use ty_python_core::{
|
||||
@@ -18,7 +19,10 @@ use crate::{
|
||||
ClassBase, ClassLiteral, ClassType, InstanceFallbackShadowsNonDataDescriptor,
|
||||
IntersectionType, KnownInstanceType, MemberLookupPolicy, StaticClassLiteral, Type,
|
||||
TypeQualifiers,
|
||||
attribute_write::{DescriptorSetterDomain, descriptor_setter_domain},
|
||||
attribute_write::{
|
||||
AttributeWriteFailure, DescriptorSetterDomain, attribute_write_requirement,
|
||||
descriptor_setter_domain,
|
||||
},
|
||||
class::CodeGeneratorKind,
|
||||
context::InferContext,
|
||||
dedicated::django,
|
||||
@@ -431,6 +435,7 @@ enum AttributeViolation<'db> {
|
||||
},
|
||||
Write {
|
||||
target: Type<'db>,
|
||||
reason: Option<AttributeWriteFailure<'db>>,
|
||||
},
|
||||
Unreadable(ReadAccess),
|
||||
ReadOnly,
|
||||
@@ -554,10 +559,12 @@ fn attribute_violation<'db>(
|
||||
} else {
|
||||
target_receiver
|
||||
};
|
||||
let receiver_writable =
|
||||
source.write.is_some() && receiver.is_attribute_writable_with(db, env, name, write);
|
||||
if !source
|
||||
.write
|
||||
.is_some_and(|source_write| write.is_assignable_to(db, env, source_write))
|
||||
|| !receiver.is_attribute_writable_with(db, env, name, write)
|
||||
|| !receiver_writable
|
||||
{
|
||||
// Do not require a write that the superclass itself cannot perform, for example
|
||||
// when a descriptor or custom `__setattr__` rejects the declared value type.
|
||||
@@ -567,7 +574,15 @@ fn attribute_violation<'db>(
|
||||
return Some(if source.write.is_none() {
|
||||
AttributeViolation::ReadOnly
|
||||
} else {
|
||||
AttributeViolation::Write { target: write }
|
||||
AttributeViolation::Write {
|
||||
target: write,
|
||||
reason: if receiver_writable {
|
||||
None
|
||||
} else {
|
||||
attribute_write_requirement(db, env, receiver, name, None)
|
||||
.failure_reason(db, env, name)
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
None
|
||||
@@ -627,11 +642,47 @@ impl<'db> AttributeOverrideViolation<'db> {
|
||||
));
|
||||
}
|
||||
}
|
||||
AttributeViolation::Write { target } => {
|
||||
AttributeViolation::Write { target, reason } => {
|
||||
diagnostic.set_primary_annotation_message(format_args!(
|
||||
"Override does not accept writes of type `{}`",
|
||||
target.display(db, env),
|
||||
));
|
||||
match reason {
|
||||
Some(AttributeWriteFailure::MissingSlot) => {
|
||||
diagnostic.info(format_args!(
|
||||
"Attribute `{name}` is not included in `__slots__`, and the class has no instance dictionary",
|
||||
));
|
||||
}
|
||||
Some(AttributeWriteFailure::SetAttr {
|
||||
definition,
|
||||
missing_slot,
|
||||
}) => {
|
||||
if missing_slot {
|
||||
diagnostic.info(format_args!(
|
||||
"Attribute `{name}` is missing from `__slots__` and the class has no \
|
||||
instance dictionary, so this override relies on `__setattr__` \
|
||||
accepting writes",
|
||||
));
|
||||
} else {
|
||||
diagnostic.info(format_args!(
|
||||
"Writes to attribute `{name}` are handled by `__setattr__`",
|
||||
));
|
||||
}
|
||||
if let Some(definition) = definition {
|
||||
let module = parsed_module(db, definition.python_file(db)).load(db);
|
||||
diagnostic.annotate(
|
||||
Annotation::secondary(Span::from(
|
||||
definition.focus_range(db, &module),
|
||||
))
|
||||
.message(format_args!(
|
||||
"This `__setattr__` does not accept writes of type `{}`",
|
||||
target.display(db, env),
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
AttributeViolation::Unreadable(access) => {
|
||||
diagnostic.set_primary_annotation_message(access.unavailable_message());
|
||||
@@ -1115,7 +1166,7 @@ pub(super) fn check_inherited_conflict<'db>(
|
||||
source.display(db, env),
|
||||
target.display(db, env),
|
||||
)),
|
||||
AttributeViolation::Write { target } => diagnostic.info(format_args!(
|
||||
AttributeViolation::Write { target, .. } => diagnostic.info(format_args!(
|
||||
"Inherited attribute does not accept writes of type `{}`",
|
||||
target.display(db, env),
|
||||
)),
|
||||
|
||||
Reference in New Issue
Block a user