Skip to content

typing ParamSpec #5837

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

Merged
merged 6 commits into from
Jun 26, 2025
Merged

typing ParamSpec #5837

merged 6 commits into from
Jun 26, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 25, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced support for Python typing constructs, including improved handling of TypeVar, ParamSpec, and TypeVarTuple, with added operator support and more accurate default value logic.
    • Introduced new properties and methods for ParamSpec, such as args and kwargs, and improved string representations for related types.
  • Bug Fixes
    • Updated test suite expectations for typing features, marking previously failing tests as expected to pass.
  • Chores
    • Updated the spelling dictionary with an additional Python-related term.

Copy link

coderabbitai bot commented Jun 25, 2025

Walkthrough

This update refines the typing module implementation and its tests. It enhances TypeVar, ParamSpec, and TypeVarTuple with improved operator support, default handling, and module attribution, introduces new helper classes, and removes expected failure decorators from typing-related tests. Additionally, a dictionary entry "bivariant" is added for spell checking.

Changes

Files/Groups Change Summary
.cspell.dict/python-more.txt Added the term "bivariant" to the Python-specific dictionary.
Lib/test/test_typing.py, Lib/test/test_types.py Removed @unittest.expectedFailure decorators from multiple typing-related tests, changing them to expected-pass.
vm/src/frame.rs Updated make_typevartuple call to accept the vm context as an argument.
vm/src/stdlib/typing.rs Major enhancements: operator support for TypeVar/ParamSpec, improved default/module logic, new helper classes, argument validation, and module attribution helpers.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PythonVM
    participant TypingModule

    User->>PythonVM: Create TypeVar/ParamSpec/TypeVarTuple
    PythonVM->>TypingModule: Call constructor with args/kwargs
    TypingModule->>TypingModule: Parse and validate arguments
    TypingModule->>TypingModule: Set default/module attributes via set_module_from_caller
    TypingModule-->>PythonVM: Return constructed object
    PythonVM-->>User: Provide typing object
Loading

Possibly related PRs

  • RustPython/RustPython#5834: Modifies the typing module, enhancing TypeVar and related constructs, with changes to constructors, default handling, and test expectations.

Suggested reviewers

  • arihant2math

Poem

In the meadow of code where type rabbits play,
New unions and defaults now hop on their way.
With args and with kwargs, and modules set right,
The tests shed their failures and leap into light.
"Bivariant" joins the lexicon,
As RustPython’s typing hops on and on!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 23aa9e0 and d6aeb8f.

📒 Files selected for processing (2)
  • Lib/test/test_types.py (0 hunks)
  • vm/src/stdlib/typing.rs (11 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_types.py
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (18)
vm/src/stdlib/typing.rs (18)

19-20: Enhanced imports for new functionality

The addition of PyNumberMethods and AsNumber, Constructor, Representable traits properly supports the new operator overloading and construction capabilities being added.


63-63: Good enhancement with AsNumber trait

Adding the AsNumber trait to the TypeVar class enables the bitwise OR operator (|) for union types, which is a valuable Python 3.10+ feature.


177-187: Proper implementation of union operator

The AsNumber implementation correctly delegates to the _make_union function for handling the | operator, following Python's typing semantics.


305-305: Good module attribution

The call to set_module_from_caller ensures proper __module__ attribute setting, aligning with CPython behavior.


344-344: Enhanced ParamSpec with comprehensive functionality

The addition of AsNumber and Constructor traits significantly improves ParamSpec's usability and Python compatibility.


351-367: Well-implemented args and kwargs properties

The implementation properly creates ParamSpecArgs and ParamSpecKwargs instances with the correct origin reference, following the typing specification.


435-454: Comprehensive typing substitution methods

The addition of typing_subst and typing_prepare_subst methods properly implements ParamSpec's substitution semantics for generic type resolution.


457-467: Consistent AsNumber implementation

The ParamSpec AsNumber implementation matches TypeVar's pattern, ensuring uniform union operator behavior across typing constructs.


469-554: Robust ParamSpec constructor implementation

The constructor properly handles argument validation, variance checking, and default value management. The error messages are clear and the logic matches Python's typing behavior.


573-573: Enhanced NoDefault with Representable trait

Adding the Representable trait improves string representation consistency for the NoDefault singleton.


610-647: Well-structured TypeVarTuple enhancement

The addition of default value support, has_default method, and reduce method brings TypeVarTuple to feature parity with other typing constructs.


649-702: Comprehensive TypeVarTuple constructor

The constructor implementation follows the same pattern as TypeVar and ParamSpec, ensuring consistent behavior and proper error handling across typing classes.


704-710: Appropriate Representable implementation

The *{name} format correctly represents TypeVarTuple instances, matching Python's typing module behavior.


712-717: Updated helper function signature

The addition of the vm parameter to make_typevartuple enables proper default value initialization with the NoDefault singleton.


724-742: Well-designed ParamSpecArgs class

The implementation includes proper origin tracking and equality comparison, essential for ParamSpec functionality in the typing system.


754-763: Informative representation method

The repr implementation intelligently formats the output based on whether the origin has a __name__ attribute, providing meaningful debugging information.


769-808: Consistent ParamSpecKwargs implementation

ParamSpecKwargs mirrors ParamSpecArgs' design pattern, ensuring uniform behavior for both parameter specification components.


863-897: Excellent module attribution implementation

The caller() and set_module_from_caller() functions properly handle module attribution with appropriate special cases for builtins and generated modules. The documentation clearly explains the differences from CPython's implementation.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f9d9307 and 23aa9e0.

📒 Files selected for processing (4)
  • .cspell.dict/python-more.txt (1 hunks)
  • Lib/test/test_typing.py (0 hunks)
  • vm/src/frame.rs (1 hunks)
  • vm/src/stdlib/typing.rs (11 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_typing.py
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (6)
.cspell.dict/python-more.txt (1)

20-20: LGTM!

The addition of "bivariant" to the spell checking dictionary is appropriate, as this term is used in the typing module's error messages.

vm/src/frame.rs (1)

1285-1285: LGTM!

The addition of the vm parameter to make_typevartuple is correct and necessary for proper initialization of the TypeVarTuple's default value.

vm/src/stdlib/typing.rs (4)

177-187: Well-implemented operator support for TypeVar!

The AsNumber trait implementation correctly delegates the | operator to the typing module's _make_union function, enabling proper union type creation.


601-710: Excellent TypeVarTuple implementation!

The implementation properly handles default values with mutex protection, includes comprehensive argument parsing and validation, and correctly integrates with the VM context for NoDefault singleton usage.


855-889: Well-implemented module attribution helpers!

The caller and set_module_from_caller functions correctly handle module attribution with appropriate special cases for builtins and special modules. The detailed comments explaining the differences from CPython's implementation are particularly helpful.


713-800: Clean implementation of ParamSpec helper classes!

ParamSpecArgs and ParamSpecKwargs are well-implemented with proper origin tracking, equality comparisons, and string representations that follow Python's typing conventions.

Comment on lines +394 to 407
if let Some(ref default_value) = self.default_value {
// Check if default_value is NoDefault (not just None)
if !default_value.is(&vm.ctx.typing_no_default) {
return Ok(default_value.clone());
}
}
// handle evaluate_default
if let Some(evaluate_default) = self.evaluate_default.clone() {
let default_value = vm.call_method(evaluate_default.as_ref(), "__call__", ())?;
let default_value = evaluate_default.call((), vm)?;
return Ok(default_value);
}
// TODO: this isn't up to spec
Ok(vm.ctx.none())
// Return NoDefault singleton
Ok(vm.ctx.typing_no_default.clone().into())
}
Copy link

@coderabbitai coderabbitai bot Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using Mutex for default_value in ParamSpec

The default_value field in ParamSpec is defined as Option<PyObjectRef> while TypeVar and TypeVarTuple use parking_lot::Mutex<PyObjectRef>. This inconsistency might cause issues if the default value needs to be computed lazily and cached. Consider using the same Mutex pattern for consistency and thread safety.

 pub(crate) struct ParamSpec {
     name: PyObjectRef,
     bound: Option<PyObjectRef>,
-    default_value: Option<PyObjectRef>,
+    default_value: parking_lot::Mutex<PyObjectRef>,
     evaluate_default: Option<PyObjectRef>,
     covariant: bool,
     contravariant: bool,
     infer_variance: bool,
 }

And update the getter accordingly:

 #[pygetset(magic)]
 fn default(&self, vm: &VirtualMachine) -> PyResult {
-    if let Some(ref default_value) = self.default_value {
-        // Check if default_value is NoDefault (not just None)
-        if !default_value.is(&vm.ctx.typing_no_default) {
-            return Ok(default_value.clone());
-        }
+    let mut default_value = self.default_value.lock();
+    // Check if default_value is NoDefault (not just None)
+    if !default_value.is(&vm.ctx.typing_no_default) {
+        return Ok(default_value.clone());
     }
     // handle evaluate_default
     if let Some(evaluate_default) = self.evaluate_default.clone() {
-        let default_value = evaluate_default.call((), vm)?;
-        return Ok(default_value);
+        *default_value = evaluate_default.call((), vm)?;
+        return Ok(default_value.clone());
     }
     // Return NoDefault singleton
     Ok(vm.ctx.typing_no_default.clone().into())
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In vm/src/stdlib/typing.rs around lines 394 to 407, the default_value field in
ParamSpec is currently an Option<PyObjectRef> but should be changed to use
parking_lot::Mutex<PyObjectRef> like in TypeVar and TypeVarTuple for thread
safety and lazy computation. Update the field definition to wrap the
default_value in a Mutex and modify the getter method to lock the mutex when
accessing or updating the default_value, ensuring consistent and safe concurrent
access.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not this time

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@youknowone Understood! I'll leave that as-is for now. Thanks for the clarification.


🧠 Learnings used
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: Follow Rust best practices for error handling and memory management when contributing to RustPython.

@youknowone youknowone requested a review from arihant2math June 25, 2025 14:34
@youknowone youknowone merged commit 6905d43 into RustPython:main Jun 26, 2025
12 checks passed
@youknowone youknowone deleted the typing branch June 26, 2025 11:31
This was referenced Jun 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant