Skip to content

Commit 33ea50c

Browse files
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.
1 parent e922722 commit 33ea50c

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

compiler/codegen/src/compile.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2254,15 +2254,6 @@ impl Compiler {
22542254
) -> CompileResult<u32> {
22552255
let mut num_annotations = 0;
22562256

2257-
// Handle return annotation first
2258-
if let Some(annotation) = returns {
2259-
self.emit_load_const(ConstantData::Str {
2260-
value: "return".into(),
2261-
});
2262-
self.compile_annotation(annotation)?;
2263-
num_annotations += 1;
2264-
}
2265-
22662257
// Handle parameter annotations
22672258
let parameters_iter = std::iter::empty()
22682259
.chain(&parameters.posonlyargs)
@@ -2282,6 +2273,15 @@ impl Compiler {
22822273
}
22832274
}
22842275

2276+
// Handle return annotation last
2277+
if let Some(annotation) = returns {
2278+
self.emit_load_const(ConstantData::Str {
2279+
value: "return".into(),
2280+
});
2281+
self.compile_annotation(annotation)?;
2282+
num_annotations += 1;
2283+
}
2284+
22852285
Ok(num_annotations)
22862286
}
22872287

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from typing import get_type_hints
2+
3+
def func(s: str) -> int:
4+
return int(s)
5+
6+
hints = get_type_hints(func)
7+
8+
# The order of type hints matters for certain functions
9+
# e.g. functools.singledispatch
10+
assert list(hints.items()) == [('s', str), ('return', int)]

0 commit comments

Comments
 (0)