-
Notifications
You must be signed in to change notification settings - Fork 1.3k
typing TypeAlias #5945
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
typing TypeAlias #5945
Conversation
WalkthroughThe changes refactor the compilation and execution of PEP 695 type alias and type parameter constructs. Direct bytecode instructions for these constructs are removed and replaced by intrinsic function calls. The stack manipulation and argument passing are updated accordingly. Additionally, new Python properties and a Changes
Sequence Diagram(s)sequenceDiagram
participant Compiler
participant VM
participant Typing
Compiler->>VM: Emit CallIntrinsic1(TypeAlias, [name, type_params, value])
VM->>Typing: TypeAliasType::new(name, type_params, value)
Typing-->>VM: TypeAliasType instance
VM-->>Compiler: Push TypeAliasType to stack
sequenceDiagram
participant Compiler
participant VM
participant Typing
Compiler->>VM: Emit CallIntrinsic1(TypeVar/ParamSpec/TypeVarTuple, args)
VM->>Typing: Create TypeVar/ParamSpec/TypeVarTuple
Typing-->>VM: Typing object
VM-->>Compiler: Push typing object to stack
Possibly related PRs
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
vm/src/frame.rs (1)
2235-2240
: Improve error message to specify expected arguments.The error message could be more descriptive about what the 3 arguments should be.
if tuple.len() != 3 { return Err(vm.new_type_error(format!( - "TypeAlias expects exactly 3 arguments, got {}", + "TypeAlias expects exactly 3 arguments (name, type_params, value), got {}", tuple.len() ))); }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
Lib/test/test_typing.py
is excluded by!Lib/**
📒 Files selected for processing (4)
compiler/codegen/src/compile.rs
(4 hunks)compiler/core/src/bytecode.rs
(3 hunks)vm/src/frame.rs
(2 hunks)vm/src/stdlib/typing.rs
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.rs`: Follow the default rustfmt code style (`cargo fmt` to format) Always ...
**/*.rs
: Follow the default rustfmt code style (cargo fmt
to format)
Always run clippy to lint code (cargo clippy
) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass
,pymodule
,pyfunction
, etc.) when implementing Python functionality in Rust
📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)
List of files the instruction was applied to:
vm/src/stdlib/typing.rs
vm/src/frame.rs
compiler/core/src/bytecode.rs
compiler/codegen/src/compile.rs
🧬 Code Graph Analysis (1)
vm/src/frame.rs (3)
vm/src/stdlib/typing.rs (1)
new
(109-115)vm/src/protocol/sequence.rs (1)
tuple
(279-289)vm/src/builtins/genericalias.rs (1)
type_params
(626-626)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: Run snippets and cpython tests (ubuntu-latest)
- GitHub Check: Run snippets and cpython tests on wasm-wasi
- GitHub Check: Run snippets and cpython tests (macos-latest)
- GitHub Check: Run tests under miri
- GitHub Check: Check the WASM package and demo
- GitHub Check: Run rust tests (windows-latest)
- GitHub Check: Ensure compilation on various targets
- GitHub Check: Run rust tests (ubuntu-latest)
- GitHub Check: Check Rust code with rustfmt and clippy
- GitHub Check: Run snippets and cpython tests (windows-latest)
- GitHub Check: Run rust tests (macos-latest)
🔇 Additional comments (11)
vm/src/stdlib/typing.rs (3)
117-120
: LGTM!The property getter correctly exposes the name field to Python.
122-125
: LGTM!The property getter correctly exposes the value field to Python.
127-130
: LGTM!The property getter correctly exposes the type_params tuple to Python.
compiler/core/src/bytecode.rs (3)
385-392
: LGTM!The intrinsic functions for type parameter handling are properly defined with sequential discriminant values.
401-403
: LGTM!The intrinsic functions for bounded and constrained type variables are properly defined.
660-660
: Confirmed LAST_INSTRUCTION updateExtendedArg is the final variant in the
Instruction
enum, so setting
const LAST_INSTRUCTION: Instruction = Instruction::ExtendedArg;
is correct. Approving the change.
- Location: compiler/core/src/bytecode.rs (lines 655–660)
compiler/codegen/src/compile.rs (3)
1070-1104
: Well-structured refactoring to use intrinsic functions.The changes correctly refactor the TypeAlias compilation to use intrinsic function calls instead of direct bytecode instructions. The addition of stack state comments improves code clarity and maintainability.
1257-1272
: Consistent refactoring of TypeVar compilation.The TypeVar and TypeVarWithBound compilation correctly uses the new intrinsic function pattern, maintaining the same functionality while aligning with the architectural shift.
1295-1327
: Uniform refactoring of remaining type parameter constructs.ParamSpec and TypeVarTuple compilation follows the same intrinsic function pattern, completing the consistent refactoring of all PEP 695 type parameter constructs.
vm/src/frame.rs (2)
2210-2228
: LGTM! Clean implementation of typing intrinsics.The TypeVar, ParamSpec, and TypeVarTuple intrinsic functions are implemented correctly, following the expected pattern for creating these typing constructs.
2277-2290
: LGTM! TypeVar variants implemented correctly.The TypeVarWithBound and TypeVarWithConstraint intrinsic functions properly handle the two-argument variants of TypeVar creation.
#[pymethod(name = "__repr__")] | ||
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { | ||
let name = self.name.str(vm)?; | ||
Ok(name.as_str().to_owned()) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Verify the repr format matches Python's TypeAliasType behavior.
The current implementation returns only the alias name. Please verify this matches the expected behavior in Python 3.12+.
🏁 Script executed:
#!/bin/bash
# Check if there are any tests that verify the __repr__ behavior
rg -A 5 "TypeAliasType.*__repr__" --type rust
rg -A 10 "test.*type.*alias.*repr" --type rust -i
Length of output: 99
🌐 Web query:
What is the expected __repr__ format for TypeAliasType in Python 3.12?
💡 Result:
In Python 3.12, the type
statement and the introduction of the TypeAliasType object in typing
provide structured, introspectable type aliases. When you define a type alias using the new syntax, for example:
type Vector = list[float]
Python internally creates an instance of TypeAliasType
named Vector
[4][2][5]. The expected __repr__
output for such a type alias reflects this new type object:
<TypeAliasType Vector>
This matches the pattern Python uses for many higher-level type objects, showing both the type (TypeAliasType
) and the alias name (Vector
). If you inspect the alias at runtime—e.g., with repr(Vector)
—you should see output in this form[4].
For TypeAliasType instances constructed manually (rare in typical library code but possible for advanced users or tools), the format is the same:
from typing import TypeAliasType
MyAlias = TypeAliasType('MyAlias', list[int], ())
repr(MyAlias)
# Output: <TypeAliasType MyAlias>
This format—<TypeAliasType AliasName>
—is standard and allows for clear introspection and debugging of type aliases in Python 3.12 and later[4].
Note: If you're using the TypeAlias
annotation (not the new type
statement), the object is just the type itself (e.g., <class 'list'>
for Vector: TypeAlias = list[float]
), not a TypeAliasType
object, so its __repr__
will be the usual for that type[4][2]. The specialized __repr__
is specific to TypeAliasType
created via the type
statement or explicitly with TypeAliasType()
.
Summary table:
Alias Definition Style | Object Type | repr Output Example |
---|---|---|
type MyAlias = list[int] |
TypeAliasType | <TypeAliasType MyAlias> |
MyAlias: TypeAlias = list[int] |
underlying type | <class 'list'> |
This behavior is consistent with Python 3.12+ static typing changes and improves the introspection of aliases during development and debugging[4][5].
Citations:
- 1: https://realpython.com/python312-typing/
- 2: https://typing.python.org/en/latest/spec/aliases.html
- 3: https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py
- 4: https://docs.python.org/3/library/typing.html
- 5: https://www.youtube.com/watch?v=YaDYUQ5mD5Q
- 6: https://docs.pydantic.dev/latest/concepts/types/
- 7: https://docs.python.org/3/library/reprlib.html
- 8: Support Python 3.12
TypeAlias
syntax ManimCommunity/manim#3772 - 9: https://typing.python.org/en/latest/spec/generics.html
- 10: https://discuss.python.org/t/why-hello-s-repr-is-hello/68320
Update __repr__
to match Python 3.12’s <TypeAliasType AliasName>
format
The current implementation returns only the alias name (e.g. "Vector"
), but Python 3.12’s TypeAliasType
should repr as <TypeAliasType Vector>
. Please update the method accordingly:
• File: vm/src/stdlib/typing.rs
Lines: 132–136
#[pymethod(name = "__repr__")]
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
- let name = self.name.str(vm)?;
- Ok(name.as_str().to_owned())
+ let name = self.name.str(vm)?;
+ Ok(format!("<TypeAliasType {}>", name.as_str()))
}
• Add a unit test (e.g. in tests/typing.rs
) to assert that
repr(type Vector = list[float]) == "<TypeAliasType Vector>"
.
This will ensure your implementation aligns with upstream Python behavior.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
#[pymethod(name = "__repr__")] | |
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { | |
let name = self.name.str(vm)?; | |
Ok(name.as_str().to_owned()) | |
} | |
#[pymethod(name = "__repr__")] | |
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { | |
let name = self.name.str(vm)?; | |
Ok(format!("<TypeAliasType {}>", name.as_str())) | |
} |
🤖 Prompt for AI Agents
In vm/src/stdlib/typing.rs lines 132 to 136, update the repr method to return a
string formatted as "<TypeAliasType AliasName>" instead of just the alias name.
Modify the code to include the fixed prefix "<TypeAliasType " and suffix ">"
around the alias name. Additionally, add a unit test in tests/typing.rs that
creates a type alias like Vector = list[float] and asserts that its repr output
equals "<TypeAliasType Vector>" to verify compliance with Python 3.12 behavior.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
>>> type A = object
>>> A
A
>>> repr(A)
'A'
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@youknowone Thank you for the correction! You're absolutely right. The current implementation in the diff is correct - it returns just the alias name as a string, which matches the actual behavior in Python 3.12.
I apologize for the confusion in my previous analysis. The web search results were misleading about the __repr__
format. Your demonstration clearly shows that repr(A)
returns 'A'
(just the alias name), not <TypeAliasType A>
.
The current implementation is working as expected and aligns with Python 3.12's actual behavior.
✏️ Learnings added
Learnt from: youknowone
PR: RustPython/RustPython#5945
File: vm/src/stdlib/typing.rs:132-136
Timestamp: 2025-07-11T07:16:06.209Z
Learning: In Python 3.12, TypeAliasType's __repr__ method returns just the alias name as a string (e.g., repr(A) returns 'A'), not the "<TypeAliasType AliasName>" format. This applies to type aliases created with the `type` statement syntax.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.858Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
Summary by CodeRabbit
New Features
__name__
,__value__
, and__type_params__
.__repr__
) for type aliases.Refactor