-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
type-comparison (E721) doesn't work when comparing against an actual type #6260
Comments
## Summary Extends `type-comparison` to flag: ```python if type(obj) is int: pass ``` In addition to the existing cases, like: ```python if type(obj) is type(1): pass ``` Closes #6260.
@charliermarsh Could you please clarify if the change here applies to only builtin types? And if so why, because in pylint it applies to any type, not just builtins: class A: ...
a = A()
type(a) == A # C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck) |
I believe that allowing arbitrary expressions on the right-hand side will lead to false positives for legitimate usages, as in: PyCQA/pycodestyle#882 (comment). |
Oh, is this because Ruff isn't able to tell if the expression on the rhs is a |
Yes that's correct. E.g., this is contrived but seems reasonable? type_of_b = type(b)
type(a) is type_of_b Pylint flags this under |
If Ruff can't determine if the rhs is a
I would write: type_of_b = type(b)
isinstance(a, type_of_b) Assuming the context is that I'm just dealing with some kind of usual operation where what I really want is a compatible subtype, and that I don't want to be checking for the exact same type. Isn't the whole point of the inspection to encourage class A: ...
class B(A): ...
b = B()
isinstace(b, A) # True
type(b) == A # False |
Would you accept a PR with the naive autofix for this? |
Yeah, we can make it a suggested fix. (Also open to further refinements on the rule logic itself, I’m not certain that our criteria is optimal given above discussion.) |
The false positive of E721 is now fixed in 0.0.283 with astral-sh/ruff@8cddb6c. See also astral-sh/ruff#6260.
the pylint rule
unidiomatic-typecheck
catches both casesThe text was updated successfully, but these errors were encountered: