这是indexloc提供的服务,不要输入任何密码
Skip to content

RUF033 fix changes the default expression’s indentation #19581

@dscorbett

Description

@dscorbett

Summary

When the fix for post-init-default (RUF033) moves and reindents the expression for a parameter’s default, it changes line-initial white space within a string literal, which changes the program’s behavior. Example:

$ cat >ruf033.py <<'# EOF'
from dataclasses import dataclass
@dataclass
class C:
    def __post_init__(self, x: int = """
    """) -> None:
        self.x = x
print(len(C().x))
# EOF

$ python ruf033.py
5

$ ruff --isolated check ruf033.py --select RUF033 --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).

$ cat ruf033.py
from dataclasses import dataclass, InitVar
@dataclass
class C:
    x: InitVar[int] = """
        """
    def __post_init__(self, x: int) -> None:
        self.x = x
print(len(C().x))

$ python ruf033.py
9

In general, even when it doesn’t change the program’s behavior, the fix’s indentation is stylistically poor. The new indentation should be the same relative to the indentation of the first line of the new InitVar attribute as the old indentation was to the indentation of the first line of the old __post_init__ parameter. For example, this:

from dataclasses import dataclass
@dataclass
class C:
    def __post_init__(self, x: tuple[int, ...] = (
        1,
        2,
    )) -> None:
        self.x = x

becomes:

from dataclasses import dataclass, InitVar
@dataclass
class C:
    x: InitVar[tuple[int, ...]] = (
            1,
            2,
        )
    def __post_init__(self, x: tuple[int, ...]) -> None:
        self.x = x

but should become:

from dataclasses import dataclass, InitVar
@dataclass
class C:
    x: InitVar[tuple[int, ...]] = (
        1,
        2,
    )
    def __post_init__(self, x: tuple[int, ...]) -> None:
        self.x = x

Version

ruff 0.12.5 (d13228a 2025-07-24)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions