Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RUF023: Sorting __match_args__ changes match semantics #9723

Closed
dosisod opened this issue Jan 30, 2024 · 1 comment · Fixed by #9724
Closed

RUF023: Sorting __match_args__ changes match semantics #9723

dosisod opened this issue Jan 30, 2024 · 1 comment · Fixed by #9724
Assignees
Labels
bug Something isn't working rule Implementing or modifying a lint rule

Comments

@dosisod
Copy link
Contributor

dosisod commented Jan 30, 2024

RUF023 should not sort __match_args__ because the order of __match_args__ affects which elements are matched against when using positional args in class patterns.

Take the following code example:

from dataclasses import dataclass

@dataclass
class UnaryExpr:
    __match_args__ = ("op", "lhs")

    op: str
    lhs: int


def is_minus_one(expr):
    match expr:
        case UnaryExpr("-", 1):
            return True

    return False


is_minus_one(UnaryExpr("-", 1))  # True
is_minus_one(UnaryExpr("+", 1))  # False

Ruff emits the following errors:

$ ruff --preview --select RUF023 file.py
file.py:6:22: RUF023 [*] `UnaryExpr.__match_args__` is not sorted

If you change __match_args__ to ("lhs", "op"), the semantics of the match statement changes, and now both is_minus_one calls return False.

@AlexWaygood
Copy link
Member

Oof, I can't believe I forgot that this was how things worked. Thanks!

@AlexWaygood AlexWaygood self-assigned this Jan 30, 2024
@AlexWaygood AlexWaygood added bug Something isn't working rule Implementing or modifying a lint rule labels Jan 30, 2024
AlexWaygood added a commit that referenced this issue Jan 30, 2024
Fixes #9723. I'm pretty embarrassed I forgot that order was important
here :(
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants