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

Fixes for unnecessary-dunder-call (PLC2801) #16216

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

VascoSch92
Copy link
Contributor

The PR addresses issue #16053

The bugs addressed are:

  • print((not 1).__add__(1))
  • try: print(list("x".__add__(y for y in "y"))) except TypeError as e: print(e)
  • print(("a" and "x").__contains__("x"))
  • print(("" or "x").__contains__("x"))
  • print(("" if False else "x").__contains__("x"))
  • print((x := "x").__contains__("y"))
  • print((not 0).__radd__(1))
  • print(3 - (2).__add__(1))
  • print("x".__add__(*"y"))

@MichaReiser I don't think I have the best implementation. Perhaps, you have some hints how to make the code better ;-)

Copy link
Contributor

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

@ntBre ntBre added bug Something isn't working fixes Related to suggested fixes for violations labels Feb 17, 2025
@MichaReiser
Copy link
Member

@VascoSch92 can you point towards the code that you think isn't ideal or can you explain me what you're trying to do?

@VascoSch92
Copy link
Contributor Author

@MichaReiser Yes my bad.

The logic behind to find a fix for a dunder call of the form a.__dunder__(b) is the following:

  1. Understand who has the precedenze between a and b, i.e., fix of the form a dunder_operation b or b dunder_operation a.

  2. Understand if one or more of a, b or the whole expression has to be wrapped in parentheses, i.e., one of the following cases:

    • (a) dunder_operation b
    • a dunder_operation (b)
    • (a dunder_operation b)
    • (a dunder_operation (b))
    • and so on...

Therefore,

  • I added a method called needs_parentheses (line 263), which determines whether an and b require parentheses. To achieve this, I simply check whether a or b contains a keyword. However, the method feels somewhat hardcoded, and there may be a more efficient way to determine if parentheses are needed.
  • Note that I did not implement all possible ramifications of the logic described above. I only implemented the ones necessary to address the bugs reported in the related issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixes Related to suggested fixes for violations
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants