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

use is_same_type when determining if a cast is redundant #18588

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
4 changes: 2 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4687,8 +4687,8 @@ def visit_cast_expr(self, expr: CastExpr) -> Type:
options = self.chk.options
if (
options.warn_redundant_casts
and not isinstance(get_proper_type(target_type), AnyType)
and source_type == target_type
and not is_same_type(target_type, AnyType(TypeOfAny.special_form))
and is_same_type(source_type, target_type)
):
self.msg.redundant_cast(target_type, expr)
if options.disallow_any_unimported and has_any_from_unimported_type(target_type):
Expand Down
26 changes: 26 additions & 0 deletions test-data/unit/check-warnings.test
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,32 @@ a: Any
b = cast(Any, a)
[builtins fixtures/list.pyi]

[case testCastToObjectNotRedunant]
# flags: --warn-redundant-casts
from typing import cast

a = 1
b = cast(object, 1)

[case testCastFromLiteralRedundant]
# flags: --warn-redundant-casts
from typing import cast

cast(int, 1)
[out]
main:4: error: Redundant cast to "int"

[case testCastFromUnionOfAnyOk]
# flags: --warn-redundant-casts
from typing import Any, cast, Union

x = Any
y = Any
z = Any

def f(q: Union[x, y, z]) -> None:
cast(Union[x, y], q)

-- Unused 'type: ignore' comments
-- ------------------------------

Expand Down