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

fix: allow f-string to trigger TRY003 #75

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

Conversation

LSanselme
Copy link

@LSanselme LSanselme commented Aug 19, 2024

Hello, and thank you for this package!

I stumble across the issue #31 and may have a potential fix.
The problem was false negative for rule TRY003, "Avoid specifying long messages outside the exception class", the root cause being the use of f-string in such messages.

The solution simply consists of checking whether the string is an f-string using ast.JoinedStr.

However, this fix is not perfect, as illustrated by the following example:

    elif a == 5:
        raise CustomException(f"code_{a}")  # This should be acceptable

This code triggers TRY003 with the fix, but it should be acceptable since there are no whitespaces, like in the existing test

    elif a == 3:
        raise CustomException("its_code_not_message")  # This is acceptable

The challenge is that, to my knowledge, there is no way to determine the content of an f-string during parsing without evaluating it first. It is probably beyond the scope of static analysis.

I think it is related to why Google discourages the use of f-string for logging in their styleguide. If f-strings are considered a bad practice for exceptions as well,, it might be worth adding a new violation rule in Tryceratops specifically for them.

Please let me know if you have any feedback or suggestions for improving this fix.

@LSanselme
Copy link
Author

LSanselme commented Aug 20, 2024

For the record, ruff's implementation of TRY003 does produce fewer false positive than this fix. Their solution involves iterating over the str elements of the f-string and trigger a violation only if any contains a whitespace:

a="0"
raise CustomException(f"code_{a}")  # This is accepted by ruff, as it should be
raise CustomException(f"message {a}")  # This is not accepted by ruff, as it should be

For the reason mentioned previously (ruff being a static linter as well), it can still produce false negative in the following case:

a = " 0"  # there is a space here
raise CustomException(f"message{a}")  # This is accepted by ruff, but it shouldn't be

[edit 2024-08-22]: I finally implemented it in 67786fb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant