Skip to content
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

[pyupgrade] Expand UP040 to handle generic functions and classes (UP040, UP046) #15565

Open
wants to merge 18 commits into
base: main
Choose a base branch
from

Conversation

ntBre
Copy link
Contributor

@ntBre ntBre commented Jan 18, 2025

Summary

This PR extends our PEP 695 handling from the type aliases handled by UP040 to generic function and class parameters, as suggested in the latter two examples from #4617:

# Input
T = TypeVar("T", bound=float)
class A(Generic[T]):
    ...

def f(t: T):
    ...

# Output
class A[T: float]:
    ...

def f[T: float](t: T):
    ...

I first implemented this as part of UP040, but based on a brief discussion during a very helpful pairing session with @AlexWaygood, I opted to split them into separate rules in the last 5 commits. From a quick look, and based on this issue, I'm pretty sure neither of these rules is currently in pyupgrade, so I just took the next available code, UP046.

The last main TODO, noted in the rule file and in the fixture, is to handle generic method parameters not included in the class itself, S in this case:

T = TypeVar("T")
S = TypeVar("S")

class Foo(Generic[T]):
    def bar(self, x: T, y: S) -> S: ...

but Alex mentioned that that might be okay to leave for a follow-up PR.

I also left a TODO about handling multiple subclasses instead of bailing out when more than one is present. I'm not sure how common that would be, but I can still handle it here, or follow up on that too.

I think this is unrelated to the PR, but when I ran cargo dev generate-all, it removed the rule code PLW0101 from ruff.schema.json. It seemed unrelated, so I left that out, but I wanted to mention it just in case.

Test Plan

New test fixture, cargo nextest run

@ntBre ntBre added the rule Implementing or modifying a lint rule label Jan 18, 2025
Copy link
Contributor

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

@ntBre ntBre added the preview Related to preview mode features label Jan 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
preview Related to preview mode features rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant