-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use type(x) == T for type narrowing (#10284)
* Use type(x) == T for type narrowing This makes mypy use expressions like type(some_expression) == some_type for type narrowing similar to how it already does for isinstance checks. This also adds some tests to make sure that this is actually being used in type narrowing. * Avoid type narrowing in the else case `type(x) == T` is False when x is an instance of a subclass of T, which isn't the same as `isinstance(x, T)`, which checks if x is an instance of T or a subclass of T. That means that x could be a subclass of T in the else case, so we can't narrow x's type to exclude this possibility. * Move check for type(x) == T to new function Refactor code for narrowing types based on checks that look like type(x) == T into a new function * Don't narrow if multiple types found Avoid narrowing in a comparison with multiple types being compared to each other even if there is a type(x) call being compared to one of them. * Avoid narrowing if no type calls found Return early if we haven't found any calls to type * Fix type signature and documentation * Add type is not equal tests Add tests to make sure that type(x) != T and type(x) is not T work as expected (the same as type(x) == T and type(x) is T but with the if and else branches switched. Currently the type(x) != T check is failing because of a mypy error about an unsupported left operand type. * Fix "Unsupported left operand type" error in tests Add fixtures to some of the tests to make mypy not show an error when we try to compare types * Narrow types in else case if type is final Final types cannot be subclassed, so it's impossible for a subclass of a final type to be used in the else case of a comparison of type(x) to a final type. That means we can narrow types in the else case the same way we would do for isinstance checks if type(x) is being compared to a final type.
- Loading branch information
1 parent
b049e6a
commit 3cebc97
Showing
2 changed files
with
178 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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