Skip to content

Commit

Permalink
fix reportInvalidCast false positive when casting to/from type
Browse files Browse the repository at this point in the history
  • Loading branch information
DetachHead committed Aug 15, 2024
1 parent 270804c commit 7b616d6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
17 changes: 9 additions & 8 deletions packages/pyright-internal/src/analyzer/typeEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10338,7 +10338,10 @@ export function createTypeEvaluator(
return false;
}

if (isInstantiableClass(leftType) || (isClassInstance(leftType) && ClassType.isBuiltIn(leftType, 'type'))) {
if (
checkEq &&
(isInstantiableClass(leftType) || (isClassInstance(leftType) && ClassType.isBuiltIn(leftType, 'type')))
) {
if (
isInstantiableClass(rightType) ||
(isClassInstance(rightType) && ClassType.isBuiltIn(rightType, 'type'))
Expand All @@ -10350,13 +10353,11 @@ export function createTypeEvaluator(
return true;
}
}
if (checkEq) {
// Does the class have an operator overload for eq?
const metaclass = leftType.shared.effectiveMetaclass;
if (metaclass && isClass(metaclass)) {
if (lookUpClassMember(metaclass, '__eq__', MemberAccessFlags.SkipObjectBaseClass)) {
return true;
}
// Does the class have an operator overload for eq?
const metaclass = leftType.shared.effectiveMetaclass;
if (metaclass && isClass(metaclass)) {
if (lookUpClassMember(metaclass, '__eq__', MemberAccessFlags.SkipObjectBaseClass)) {
return true;
}
}

Expand Down
10 changes: 8 additions & 2 deletions packages/pyright-internal/src/tests/samples/cast.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import cast, Never
from typing import Any, cast, Never
from collections.abc import Mapping

def foo(str_: str, int_or_str: int | str, dict_int_or_none: dict[str, int | None], mapping: Mapping[str, int | None]):
def foo(str_: str, int_or_str: int | str, dict_int_or_none: dict[str, int | None], mapping: Mapping[str, int | None], type_int: type[int], type_any: type[Any], type_object: type[object]):
cast(int, str_) # error, non-overlapping types
cast(int | bytes, str_) # error, non-overlapping types
cast(object, str_) # wider, no error
Expand All @@ -13,3 +13,9 @@ def foo(str_: str, int_or_str: int | str, dict_int_or_none: dict[str, int | None
cast(Mapping[str, int], dict_int_or_none) # wider (ignore type parameters), no error
cast(dict[str, int], mapping) # wider, no error
cast(dict[str, bytes], mapping) # xfail, https://github.com/DetachHead/basedpyright/issues/259
cast(type[Any], object()) # narrower, no error
cast(type[object], object()) # narrower, no error
cast(type[int], object()) # narrower, no error
cast(object, type_any) # wider, no error
cast(object, type_object) # wider, no error
cast(object, type_int) # wider, no error

0 comments on commit 7b616d6

Please sign in to comment.