astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.37k stars 1.08k forks source link

UP007: autofix does not work for some examples #4843

Open saippuakauppias opened 1 year ago

saippuakauppias commented 1 year ago

Example:

from typing import Any, Dict, Optional, Type, Union

# 1
DataType = Optional[Dict[str, Any]]

# 2
class StatusedModel:
    ACTIVE: str = 'active'
    BLOCKED: str = 'blocked'
    DELETED: str = 'deleted'

StatusType = Union[StatusedModel.ACTIVE, StatusedModel.BLOCKED, StatusedModel.DELETED]

# 3
BALANCE_ZERO = 'zero'
BALANCE_LOW = 'low'
ModeType = Union[BALANCE_LOW, BALANCE_ZERO]

# 4
Numeric = Union[int, float, str]

# 5
IdType = Union[int, Type[int]]

Run output:

$ ruff --fix --select UP007 ruff_errors/UP007.py
ruff_errors/UP007.py:5:12: UP007 Use `X | Y` for type annotations
ruff_errors/UP007.py:15:14: UP007 Use `X | Y` for type annotations
ruff_errors/UP007.py:21:12: UP007 Use `X | Y` for type annotations
ruff_errors/UP007.py:25:11: UP007 Use `X | Y` for type annotations
ruff_errors/UP007.py:29:10: UP007 Use `X | Y` for type annotations
Found 5 errors.
charliermarsh commented 1 year ago

These are intentional, right now we don't autofix UP007 errors that are used outside of annotations (e.g., on the right-hand side of an assignment). (pyupgrade doesn't either.)

Its caused some subtle bugs in the past: https://github.com/charliermarsh/ruff/issues/3215, https://github.com/charliermarsh/ruff/issues/2981. It was also discussed here: https://github.com/charliermarsh/ruff/issues/4108.

It's possible that it's actually fine to fix these, with the exception that we can't rewrite Union[new_types] to new_types. I'm not certain.

Hnasar commented 6 months ago

It would be very helpful to autofix the PEP604 | unions, but have it gated behind an unsafe fix. I'm using --add-noqa as a workaround for now.