Skip to content

Conversation

konn
Copy link
Collaborator

@konn konn commented Aug 27, 2025

Summary

This PR adds support for # type: ignore comments in generated Python stub files, enabling developers to suppress specific type checker warnings from MyPy and Pyright.

Key Features

  • Comprehensive rule support: 70+ predefined MyPy error codes and Pyright diagnostic rules
  • Custom rule fallback: Unknown rules are preserved as Custom variants
  • Dual target support: Works for both standalone functions and class methods
  • Compile-time validation: Warnings for empty rule lists and unknown rules
  • Clean syntax: #[gen_stub(type_ignore = ["rule1", "rule2"])] attribute

Usage Examples

// Functions
#[gen_stub_pyfunction]
#[gen_stub(type_ignore = ["arg-type", "return-value"])]
#[pyfunction]
fn my_function() -> i32 { 42 }

// Methods
#[pymethods]
#[gen_stub_pymethods]
impl MyClass {
    #[gen_stub(type_ignore = ["union-attr", "return-value"])]
    fn my_method(&self) -> i32 { 42 }
}

Generated Output

def my_function() -> builtins.int:  # type: ignore[arg-type,return-value]
    """Function docstring"""

class MyClass:
    def my_method(self) -> builtins.int:  # type: ignore[union-attr,return-value]
        """Method docstring"""

Implementation Details

  • New module: type_check_rule.rs with comprehensive RuleName enum
  • Extended data structures: Added type_ignored field to PyFunctionInfo and MethodInfo
  • Proc-macro support: Enhanced attribute parsing for type_ignore parameter
  • Standard traits: Implements FromStr and Display for RuleName
  • Backward compatibility: No breaking changes to existing APIs

Supported Rule Categories

  • MyPy error codes: arg-type, return-value, attr-defined, union-attr, etc.
  • Pyright diagnostics: reportGeneralTypeIssues, reportReturnType, etc.
  • Custom rules: Any unknown rule name is preserved for future compatibility

Test Coverage

  • Comprehensive test cases for functions and methods
  • Validation of MyPy and Pyright rule parsing
  • Custom rule handling verification
  • Warning generation for empty rule lists

🤖 Generated with Claude Code

konn and others added 2 commits August 27, 2025 11:31
Implements #[gen_stub(type_ignore = [...])] attribute to generate
Python type checker ignore comments for both functions and methods.

Features:
- Comprehensive RuleName enum with 70+ MyPy and Pyright error codes
- Support for custom unknown rules via Custom(String) variant
- Generates "# type: ignore[rule1,rule2]" comments on function/method definitions
- Compile-time warnings for empty rule lists and unknown rules
- Works for both standalone functions and class methods
- Dual attribute location parsing (Function/Field) for method compatibility

Implementation:
- New type_check_rule.rs module with complete rule definitions
- Extended PyFunctionInfo and MethodInfo structs with type_ignored field
- Updated proc-macro parsing to handle type_ignore attribute
- Modified stub generation to append ignore comments to def lines
- Added comprehensive test cases for functions and methods

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Replace custom from_str method with standard FromStr trait implementation
to avoid clippy warning about method name confusion with std::str::FromStr.

Changes:
- Implement FromStr trait for RuleName with proper error handling
- Remove custom from_str method that caused clippy warning
- Update generation code to use .parse() instead of RuleName::from_str()
- Update tests to use standard .parse() method

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@Copilot Copilot AI review requested due to automatic review settings August 27, 2025 02:39
@konn konn marked this pull request as draft August 27, 2025 02:40
Copilot

This comment was marked as outdated.

konn and others added 7 commits August 27, 2025 11:46
- Fix import in method.rs from type_check_rule::RuleName to rule_name::RuleName
- Add missing type_ignored field to MethodDef struct in doctest

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Added 15 missing Pyright diagnostic rules:
- reportNoOverloadImplementation
- reportTypeCommentUsage
- reportConstantRedefinition
- reportInconsistentConstructor
- reportOverlappingOverload
- reportMissingSuperCall
- reportUninitializedInstanceVariable
- reportCallInDefaultInitializer
- reportAssertAlwaysTrue
- reportSelfClsParameterName
- reportUnhashable
- reportUnusedCallResult
- reportUnusedExcept
- reportUnusedExpression
- reportUnreachable

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@konn konn requested a review from Copilot August 27, 2025 03:12
Copilot

This comment was marked as outdated.

@konn konn requested a review from Copilot August 27, 2025 03:14
Copilot

This comment was marked as outdated.

@konn konn requested a review from Copilot August 27, 2025 03:24
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds comprehensive support for generating # type: ignore comments in Python stub files, enabling developers to suppress specific type checker warnings from MyPy and Pyright. The implementation includes a new rule name system with 70+ predefined error codes and custom rule support.

Key changes:

  • New RuleName enum with comprehensive MyPy and Pyright diagnostic rule support
  • Enhanced proc-macro attribute parsing for type_ignore parameter
  • Extended data structures to store type ignore rules in function and method metadata

Reviewed Changes

Copilot reviewed 13 out of 14 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
pyo3-stub-gen/src/type_info.rs Added type_ignored field to MethodInfo and PyFunctionInfo structs
pyo3-stub-gen/src/rule_name.rs New module defining comprehensive RuleName enum with MyPy/Pyright rules
pyo3-stub-gen/src/lib.rs Added rule_name module export
pyo3-stub-gen/src/generate/function.rs Enhanced function generation with type ignore comment support
pyo3-stub-gen/src/generate/method.rs Enhanced method generation with type ignore comment support
pyo3-stub-gen/src/generate/class.rs Updated auto-generated methods to include None type_ignored field
pyo3-stub-gen/src/generate/variant_methods.rs Updated variant methods to include None type_ignored field
pyo3-stub-gen-derive/src/gen_stub/pyfunction.rs Added type_ignore attribute parsing for functions
pyo3-stub-gen-derive/src/gen_stub/method.rs Added type_ignore attribute parsing for methods
pyo3-stub-gen-derive/src/gen_stub/attr.rs Enhanced attribute parser with TypeIgnore variant
examples/pure/src/lib.rs Added comprehensive test cases for type ignore functionality
examples/pure/pure.pyi Generated stub examples showing type ignore comments

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@konn konn marked this pull request as ready for review August 27, 2025 03:34
@konn konn requested a review from termoshtt August 27, 2025 03:34
konn and others added 6 commits August 27, 2025 16:00
- Introduce IgnoreTarget enum with All and Specified variants
- Support #[gen_stub(type_ignore)] syntax for catch-all ignore
- Support #[gen_stub(type_ignore = ["rule1", "rule2"])] for specific rules
- Add validation to reject empty Specified arrays
- Update stub generation to emit correct type ignore comments
- Replace confusing Some(vec![]) behavior with explicit enum variants

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Added trybuild test case to verify that using #[gen_stub(type_ignore=[])]
on Python functions results in the expected compilation error with helpful
error message guidance.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@konn konn requested a review from termoshtt August 27, 2025 08:15
@konn konn enabled auto-merge (squash) August 27, 2025 08:19
Copy link
Member

@termoshtt termoshtt left a comment

Choose a reason for hiding this comment

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

LGTM

@konn konn merged commit 1ebc13c into main Aug 27, 2025
26 checks passed
@konn konn deleted the konn/type-ignore-attribute branch August 27, 2025 08:31
benruijl pushed a commit to benruijl/pyo3-stub-gen that referenced this pull request Aug 29, 2025
…nc#279)

## Summary

This PR adds support for `# type: ignore` comments in generated Python
stub files, enabling developers to suppress specific type checker
warnings from MyPy and Pyright.

### Key Features

- **Comprehensive rule support**: 70+ predefined MyPy error codes and
Pyright diagnostic rules
- **Custom rule fallback**: Unknown rules are preserved as Custom
variants
- **Dual target support**: Works for both standalone functions and class
methods
- **Compile-time validation**: Warnings for empty rule lists and unknown
rules
- **Clean syntax**: `#[gen_stub(type_ignore = ["rule1", "rule2"])]`
attribute

### Usage Examples

```rust
// Functions
#[gen_stub_pyfunction]
#[gen_stub(type_ignore = ["arg-type", "return-value"])]
#[pyfunction]
fn my_function() -> i32 { 42 }

// Methods
#[pymethods]
#[gen_stub_pymethods]
impl MyClass {
    #[gen_stub(type_ignore = ["union-attr", "return-value"])]
    fn my_method(&self) -> i32 { 42 }
}
```

### Generated Output

```python
def my_function() -> builtins.int:  # type: ignore[arg-type,return-value]
    """Function docstring"""

class MyClass:
    def my_method(self) -> builtins.int:  # type: ignore[union-attr,return-value]
        """Method docstring"""
```

### Implementation Details

- **New module**: `type_check_rule.rs` with comprehensive `RuleName`
enum
- **Extended data structures**: Added `type_ignored` field to
`PyFunctionInfo` and `MethodInfo`
- **Proc-macro support**: Enhanced attribute parsing for `type_ignore`
parameter
- **Standard traits**: Implements `FromStr` and `Display` for `RuleName`
- **Backward compatibility**: No breaking changes to existing APIs

### Supported Rule Categories

- **MyPy error codes**: `arg-type`, `return-value`, `attr-defined`,
`union-attr`, etc.
- **Pyright diagnostics**: `reportGeneralTypeIssues`,
`reportReturnType`, etc.
- **Custom rules**: Any unknown rule name is preserved for future
compatibility

### Test Coverage

- Comprehensive test cases for functions and methods
- Validation of MyPy and Pyright rule parsing
- Custom rule handling verification
- Warning generation for empty rule lists

🤖 Generated with [Claude Code](https://claude.ai/code)

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Copilot <[email protected]>
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.

2 participants