Skip to content

Ruff rewrites Union[tuple_of_types] in potentially breaking ways #3215

@rouge8

Description

@rouge8

After Ruff rewrites this file, Python starts throwing an error.

t.py

from typing import Union, cast


def _make_optional(cls: type) -> type:
    """Convert a type to an Optional type."""
    return cast(type, cls | None)


new_types = (int, float)

_make_optional(cast(type, Union[new_types]))

output

❯ ruff --isolated --fix --target-version py311 --select UP t.py
Found 1 error (1 fixed, 0 remaining).

rewritten

from typing import Union, cast


def _make_optional(cls: type) -> type:
    """Convert a type to an Optional type."""
    return cast(type, cls | None)


new_types = (int, float)

_make_optional(cast(type, new_types))

Unfortunately, t.py now errors out:

Traceback (most recent call last):
  File "/Users/andyfreeland/t.py", line 11, in <module>
    _make_optional(cast(type, new_types))
  File "/Users/andyfreeland/t.py", line 6, in _make_optional
    return cast(type, cls | None)
                      ~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'tuple' and 'NoneType'

version

ruff 0.0.252

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions