Skip to content

Commit

Permalink
Merge pull request #839 from asottile/typevar-bounds-563
Browse files Browse the repository at this point in the history
support PEP 563 rewrites for 3.12+ TypeVar bounds
  • Loading branch information
asottile authored Jun 10, 2023
2 parents 77a8c2c + 06207f6 commit 90c2ec5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pyupgrade/_plugins/typing_pep563.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,16 @@ def visit_AnnAssign(
if not _supported_version(state):
return
yield from _replace_string_literal(node.annotation)


if sys.version_info >= (3, 12): # pragma: >=3.12 cover
@register(ast.TypeVar)
def visit_TypeVar(
state: State,
node: ast.TypeVar,
parent: ast.AST,
) -> Iterable[tuple[Offset, TokenFunc]]:
if not _supported_version(state):
return
if node.bound is not None:
yield from _replace_string_literal(node.bound)
27 changes: 27 additions & 0 deletions tests/features/typing_pep563_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import sys

import pytest

from pyupgrade._data import Settings
Expand Down Expand Up @@ -54,6 +56,15 @@
'x: Annotated[1:2] = ...\n',
id='Annotated with invalid slice',
),
pytest.param(
'def f[X: "int"](x: X) -> X: return x\n',
id='TypeVar quoted bound but no __future__ annotations',
),
pytest.param(
'from __future__ import annotations\n'
'def f[X](x: X) -> X: return x\n',
id='TypeVar without bound',
),
),
)
def test_fix_typing_pep563_noop(s):
Expand Down Expand Up @@ -363,3 +374,19 @@ def test_fix_typing_pep563_noop(s):
def test_fix_typing_pep563(s, expected):
ret = _fix_plugins(s, settings=Settings(min_version=(3, 7)))
assert ret == expected


@pytest.mark.xfail(sys.version_info < (3, 12), reason='3.12+ syntax')
def test_typevar_bound():
src = '''\
from __future__ import annotations
def f[T: "int"](t: T) -> T:
return t
'''
expected = '''\
from __future__ import annotations
def f[T: int](t: T) -> T:
return t
'''
ret = _fix_plugins(src, settings=Settings())
assert ret == expected

0 comments on commit 90c2ec5

Please sign in to comment.