Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/pyrefly_config/src/error_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,8 @@ pub enum ErrorKind {
/// Identity comparison (`is` or `is not`) between types that are provably disjoint
/// or between literals whose comparison result is statically known.
UnnecessaryComparison,
/// Warning when calling a builtin type constructor (str, int, float, bytes) on a value that is already of that type.
UnnecessaryTypeConversion,
/// A return or yield that can never be reached.
/// This occurs when a return/yield follows a statement that always exits,
/// such as return, raise, break, or continue.
Expand Down Expand Up @@ -359,6 +361,7 @@ impl ErrorKind {
ErrorKind::UnannotatedParameter => Severity::Ignore,
ErrorKind::UnannotatedReturn => Severity::Ignore,
ErrorKind::UnnecessaryComparison => Severity::Warn,
ErrorKind::UnnecessaryTypeConversion => Severity::Warn,
ErrorKind::Unreachable => Severity::Warn,
ErrorKind::UnresolvableDunderAll => Severity::Warn,
ErrorKind::UntypedImport => Severity::Warn,
Expand Down
32 changes: 32 additions & 0 deletions pyrefly/lib/alt/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,37 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
}
}

fn check_unnecessary_type_conversion(
&self,
cls: &ClassType,
args: &[CallArg],
range: TextRange,
errors: &ErrorCollector,
) {
let builtin_names = ["str", "int", "float", "bytes"];
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bool should be added to the built_in names here

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding bool here causes test_bool_special_exports_bug to fail, where bool(x) is used in a conditional for type narrowing so it does not seem to be redundant. Happy to include it if we want to change that behavior, but wanted to flag this first.

Copy link
Copy Markdown
Contributor

@NathanTempest NathanTempest Apr 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think bool should be included in the lint. I think that the narrowing argument doesn't hold up. The test test_bool_special_exports_bug in generic_legacy.rs:820 shows:

def f(x: bool):
    if bool(x):
        assert_type(x, Literal[True])

But this narrowing comes from the if statement, not from bool(). Writing if x: produces the exact same narrowing because bool(x) is a no-op here. The lint flagging it as unnecessary would actually be correct since the user could just write if x:

At runtime, bool(x) where x: bool is always a no-op , bool.new returns the same object unchanged. This is unlike bool(x) where x: str | None, which performs meaningful truthiness coercion and would not be flagged by this lint (since str | None != bool).

No other tool catches this today. Neither mypy, pyright, ruff, nor pylint flag bool(x) where x: bool. Adding it to pyrefly would be novel but correct and being comprehensive is a reasonable goal for a type checker.

One edge case to consider: bool(x) where x: Literal[True] is arguably not redundant since Literal[True] != bool the call widens the type. The lint should only fire when the argument type is exactly bool, not a Literal bool. Worth adding a test for this:

from typing import Literal
def f(x: Literal[True]) -> None:
    y = bool(x)  # OK - Literal[True] is not exactly bool

How about we implement this and check the mypy_primer results to see if any tests change. If the primer comes back clean, we have strong evidence that this doesn't cause false positives in real-world code. If it does flag something, we can use those concrete examples to decide whether to exclude bool or refine the lint.

if !builtin_names
.iter()
.any(|name| cls.has_qname("builtins", name))
{
return;
}
if let Some(arg_ty) = self.first_arg_type(args, errors) {
let target_ty = self.heap.mk_class_type(cls.clone());
if !arg_ty.is_any() && arg_ty == target_ty {
self.error(
errors,
range,
ErrorInfo::Kind(ErrorKind::UnnecessaryTypeConversion),
format!(
"Unnecessary `{}()` call; argument is already of type `{}`",
cls.name(),
arg_ty.deterministic_printing(),
),
);
}
}
}

fn call_infer_with_callee_range(
&self,
call_target: CallTarget,
Expand Down Expand Up @@ -1092,6 +1123,7 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
}
}
};
self.check_unnecessary_type_conversion(&cls, args, arguments_range, errors);
let constructed_type = self.construct_class(
cls,
constructor_kind,
Expand Down
1 change: 1 addition & 0 deletions pyrefly/lib/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ mod typed_dict;
mod typeform;
mod typing_self;
mod unnecessary_comparison;
mod unnecessary_type_conversion;
mod untyped_def_behaviors;
pub mod util;
mod var_resolution;
Expand Down
73 changes: 73 additions & 0 deletions pyrefly/lib/test/unnecessary_type_conversion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

use crate::testcase;

testcase!(
test_str_to_str,
r#"
def f(x: str) -> None:
y = str(x) # E: Unnecessary `str()` call; argument is already of type `str`
"#,
);

testcase!(
test_int_to_int,
r#"
def f(x: int) -> None:
y = int(x) # E: Unnecessary `int()` call; argument is already of type `int`
"#,
);

testcase!(
test_float_to_float,
r#"
def f(x: float) -> None:
y = float(x) # E: Unnecessary `float()` call; argument is already of type `float`
"#,
);

testcase!(
test_int_to_str_ok,
r#"
def f(x: int) -> None:
y = str(x) # OK - converting int to str
"#,
);

testcase!(
test_bool_to_int_ok,
r#"
def f(x: bool) -> None:
y = int(x) # OK - bool is a subtype of int, types are not equal
"#,
);

testcase!(
test_any_ok,
r#"
from typing import Any
def f(x: Any) -> None:
y = str(x) # OK - argument is Any, type is unknown
"#,
);

testcase!(
test_bytes_to_bytes,
r#"
def f(x: bytes) -> None:
y = bytes(x) # E: Unnecessary `bytes()` call; argument is already of type `bytes`
"#,
);

testcase!(
test_no_args_ok,
r#"
def f() -> None:
y = str() # OK - no argument
"#,
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good test coverage but could you also add few cases:

bool(x) where x: bool — should warn (if bool is added to the checked types)
bytes(x) where x: bytes — same reasoning

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bytes is added but bool is not, we are just trying to be as comprehensive as possible for our typechecker

11 changes: 11 additions & 0 deletions website/docs/error-kinds.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1372,6 +1372,17 @@ def test1(x: object) -> None:

This check is relatively conservative and only warns on limited cases where the comparison is highly likely to be redundant.

## unnecessary-type-conversion

This warning is raised when a builtin type constructor (`str`, `int`, `float`, or `bool`) is called on a value that is already of that type, making the conversion redundant.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add bytes to this built in types


The default severity of this diagnostic is `warn`.

```python
def f(x: str) -> None:
y = str(x) # unnecessary-type-conversion: `x` is already of type `str`
```

## unreachable

This error is raised when a `return` or `yield` can never be reached because it comes
Expand Down
Loading