Merged
Conversation
A cast is considered redundant if the target type of the cast is the same as the inferred type of the expression. A cast to a supertype like `cast(object, 1)` is not considered redundant because such a cast could be needed to work around deficiencies in type inference. Fixes python#958.
c665ad2 to
bea5792
Compare
Collaborator
|
Looks good! |
carljm
pushed a commit
to astral-sh/ruff
that referenced
this pull request
Apr 1, 2025
## Summary Following up from earlier discussion on Discord, this PR adds logic to flag casts as redundant when the inferred type of the expression is the same as the target type. It should follow the semantics from [mypy](python/mypy#1705). Example: ```python def f() -> int: return 10 # error: [redundant-cast] "Value is already of type `int`" cast(int, f()) ```
hauntsaninja
pushed a commit
that referenced
this pull request
Apr 22, 2025
while working on #18540 (which my original prototype based the code on `warn-redundant-casts`) I noticed the suggestion [here](#18540 (comment)) would probably make sense to apply to redundant-cast as well! I also made sure to include the example from the [original implementation](#1705 (comment)) just to make sure I wasn't regressing that as well since it seemed related.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A cast is considered redundant if the target type of the cast is the
same as the inferred type of the expression. A cast to a supertype
like
cast(object, 1)is not considered redundant because such a castcould be needed to work around deficiencies in type inference.
Fixes #958.