Remove 'non-obvious' allowance for E721 (#12300)

## Summary

I don't fully understand the purpose of this. In #7905, it was just
copied over from the previous non-preview implementation. But it means
that (e.g.) we don't treat `type(self.foo)` as a type -- which is wrong.

Closes https://github.com/astral-sh/ruff/issues/12290.
This commit is contained in:
Charlie Marsh 2024-07-12 06:21:43 -07:00 committed by GitHub
parent 4e6ecb2348
commit aa5c53b38b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 12 additions and 16 deletions

View file

@ -16,10 +16,7 @@ use crate::checkers::ast::Checker;
/// Unlike a direct type comparison, `isinstance` will also check if an object /// Unlike a direct type comparison, `isinstance` will also check if an object
/// is an instance of a class or a subclass thereof. /// is an instance of a class or a subclass thereof.
/// ///
/// Under [preview mode](https://docs.astral.sh/ruff/preview), this rule also /// If you want to check for an exact type match, use `is` or `is not`.
/// allows for direct type comparisons using `is` and `is not`, to check for
/// exact type equality (while still forbidding comparisons using `==` and
/// `!=`).
/// ///
/// ## Example /// ## Example
/// ```python /// ```python
@ -74,18 +71,7 @@ pub(crate) fn type_comparison(checker: &mut Checker, compare: &ast::ExprCompare)
/// Returns `true` if the [`Expr`] is known to evaluate to a type (e.g., `int`, or `type(1)`). /// Returns `true` if the [`Expr`] is known to evaluate to a type (e.g., `int`, or `type(1)`).
fn is_type(expr: &Expr, semantic: &SemanticModel) -> bool { fn is_type(expr: &Expr, semantic: &SemanticModel) -> bool {
match expr { match expr {
Expr::Call(ast::ExprCall { Expr::Call(ast::ExprCall { func, .. }) => {
func, arguments, ..
}) => {
// Allow comparison for types which are not obvious.
if !arguments
.args
.first()
.is_some_and(|arg| !arg.is_name_expr() && !arg.is_none_literal_expr())
{
return false;
}
// Ex) `type(obj) == type(1)` // Ex) `type(obj) == type(1)`
semantic.match_builtin_expr(func, "type") semantic.match_builtin_expr(func, "type")
} }

View file

@ -40,6 +40,16 @@ E721.py:21:8: E721 Use `is` and `is not` for type comparisons, or `isinstance()`
23 | assert type(res) == type([]) 23 | assert type(res) == type([])
| |
E721.py:21:36: E721 Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance checks
|
19 | pass
20 | #: E721
21 | assert type(res) == type(False) or type(res) == type(None)
| ^^^^^^^^^^^^^^^^^^^^^^^ E721
22 | #: E721
23 | assert type(res) == type([])
|
E721.py:23:8: E721 Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance checks E721.py:23:8: E721 Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance checks
| |
21 | assert type(res) == type(False) or type(res) == type(None) 21 | assert type(res) == type(False) or type(res) == type(None)