ruff/crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_0.py
Brent Westbrook 6bb32355ef
[pyupgrade] Rename private type parameters in PEP 695 generics (UP049) (#15862)
## Summary

This is a new rule to implement the renaming of PEP 695 type parameters
with leading underscores after they have (presumably) been converted
from standalone type variables by either UP046 or UP047. Part of #15642.

I'm not 100% sure the fix is always safe, but I haven't come up with any
counterexamples yet. `Renamer` seems pretty precise, so I don't think
the usual issues with comments apply.

I initially tried writing this as a rule that receives a `Stmt` rather
than a `Binding`, but in that case the
`checker.semantic().current_scope()` was the global scope, rather than
the scope of the type parameters as I needed. Most of the other rules
using `Renamer` also used `Binding`s, but it does have the downside of
offering separate diagnostics for each parameter to rename.

## Test Plan

New snapshot tests for UP049 alone and the combination of UP046, UP049,
and PYI018.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-02-04 13:22:57 -05:00

30 lines
578 B
Python

# simple case, replace _T in signature and body
class Generic[_T]:
buf: list[_T]
def append(self, t: _T):
self.buf.append(t)
# simple case, replace _T in signature and body
def second[_T](var: tuple[_T]) -> _T:
y: _T = var[1]
return y
# one diagnostic for each variable, comments are preserved
def many_generics[
_T, # first generic
_U, # second generic
](args):
return args
# neither of these are currently renamed
from typing import Literal, cast
def f[_T](v):
cast("_T", v)
cast("Literal['_T']")
cast("list[_T]", v)