Skip to content

Commit e8755a7

Browse files
committed
Add set annotations for type
1 parent c85b93a commit e8755a7

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

vm/src/builtins/type.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,34 @@ impl PyType {
549549
Ok(annotations)
550550
}
551551

552+
#[pygetset(magic, setter)]
553+
fn set_annotations(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
554+
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
555+
return Err(vm.new_type_error(format!(
556+
"cannot set '__annotations__' attribute of immutable type '{}'",
557+
self.name()
558+
)));
559+
}
560+
561+
let __annotations__ = identifier!(vm, __annotations__);
562+
if let Some(value) = value {
563+
self.attributes.write().insert(__annotations__, value);
564+
} else {
565+
self.attributes
566+
.read()
567+
.get(__annotations__)
568+
.cloned()
569+
.ok_or_else(|| {
570+
vm.new_attribute_error(format!(
571+
"'{}' object has no attribute '__annotations__'",
572+
self.name()
573+
))
574+
})?;
575+
}
576+
577+
Ok(())
578+
}
579+
552580
#[pygetset(magic)]
553581
pub fn module(&self, vm: &VirtualMachine) -> PyObjectRef {
554582
self.attributes

vm/src/types/slot.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ impl std::fmt::Debug for PyTypeSlots {
105105
bitflags! {
106106
#[non_exhaustive]
107107
pub struct PyTypeFlags: u64 {
108+
const IMMUTABLETYPE = 1 << 8;
108109
const HEAPTYPE = 1 << 9;
109110
const BASETYPE = 1 << 10;
110111
const METHOD_DESCR = 1 << 17;

0 commit comments

Comments
 (0)