Add return annotation to __annotations__ last (#6071)

Functions like `functools.singledispatch` are sensitive to the order of
items in the `__annotations__` map.

CPython puts returns last.
This commit is contained in:
Jack O'Connor authored and GitHub committed 2025-08-08 23:31:12 +09:00
1 parent e922722191
commit 33ea50c2e9
2 files changed
+19 -9

No files matched your search

+9 -9
View File
@@ -2254,15 +2254,6 @@ impl Compiler {
) -> CompileResult<u32> {
let mut num_annotations = 0;
// Handle return annotation first
if let Some(annotation) = returns {
self.emit_load_const(ConstantData::Str {
value: "return".into(),
});
self.compile_annotation(annotation)?;
num_annotations += 1;
}
// Handle parameter annotations
let parameters_iter = std::iter::empty()
.chain(&parameters.posonlyargs)
@@ -2282,6 +2273,15 @@ impl Compiler {
}
}
// Handle return annotation last
if let Some(annotation) = returns {
self.emit_load_const(ConstantData::Str {
value: "return".into(),
});
self.compile_annotation(annotation)?;
num_annotations += 1;
}
Ok(num_annotations)
}
@@ -0,0 +1,10 @@
from typing import get_type_hints
def func(s: str) -> int:
return int(s)
hints = get_type_hints(func)
# The order of type hints matters for certain functions
# e.g. functools.singledispatch
assert list(hints.items()) == [('s', str), ('return', int)]