From bcb3747f277745f7a0035bb92cc95ee83f6778dc Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Fri, 1 Mar 2024 06:01:34 -0800 Subject: [PATCH] Implement TypeIs (PEP 742) (#16898) Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com> --- docs/source/error_code_list2.rst | 16 + mypy/applytype.py | 7 +- mypy/checker.py | 42 +- mypy/checkexpr.py | 13 +- mypy/constraints.py | 16 +- mypy/errorcodes.py | 6 + mypy/expandtype.py | 2 + mypy/fixup.py | 2 + mypy/message_registry.py | 5 +- mypy/messages.py | 4 + mypy/nodes.py | 3 + mypy/semanal.py | 7 + mypy/subtypes.py | 13 + mypy/typeanal.py | 27 +- mypy/types.py | 9 + test-data/unit/check-errorcodes.test | 8 + test-data/unit/check-typeguard.test | 2 +- test-data/unit/check-typeis.test | 798 ++++++++++++++++++ test-data/unit/lib-stub/typing_extensions.pyi | 1 + 19 files changed, 962 insertions(+), 19 deletions(-) create mode 100644 test-data/unit/check-typeis.test diff --git a/docs/source/error_code_list2.rst b/docs/source/error_code_list2.rst index c966fe1f7ea6..465d1c7a6583 100644 --- a/docs/source/error_code_list2.rst +++ b/docs/source/error_code_list2.rst @@ -555,3 +555,19 @@ Correct usage: When this code is enabled, using ``reveal_locals`` is always an error, because there's no way one can import it. + +.. _code-narrowed-type-not-subtype: + +Check that ``TypeIs`` narrows types [narrowed-type-not-subtype] +--------------------------------------------------------------- + +:pep:`742` requires that when ``TypeIs`` is used, the narrowed +type must be a subtype of the original type:: + + from typing_extensions import TypeIs + + def f(x: int) -> TypeIs[str]: # Error, str is not a subtype of int + ... + + def g(x: object) -> TypeIs[str]: # OK + ... diff --git a/mypy/applytype.py b/mypy/applytype.py index e14906fa2772..eecd555bf90d 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -137,11 +137,15 @@ def apply_generic_arguments( arg_types=[expand_type(at, id_to_type) for at in callable.arg_types] ) - # Apply arguments to TypeGuard if any. + # Apply arguments to TypeGuard and TypeIs if any. if callable.type_guard is not None: type_guard = expand_type(callable.type_guard, id_to_type) else: type_guard = None + if callable.type_is is not None: + type_is = expand_type(callable.type_is, id_to_type) + else: + type_is = None # The callable may retain some type vars if only some were applied. # TODO: move apply_poly() logic from checkexpr.py here when new inference @@ -164,4 +168,5 @@ def apply_generic_arguments( ret_type=expand_type(callable.ret_type, id_to_type), variables=remaining_tvars, type_guard=type_guard, + type_is=type_is, ) diff --git a/mypy/checker.py b/mypy/checker.py index a272a3aaac3d..941dc06f1c71 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -1203,6 +1203,22 @@ def check_func_def( # visible from *inside* of this function/method. ref_type: Type | None = self.scope.active_self_type() + if typ.type_is: + arg_index = 0 + # For methods and classmethods, we want the second parameter + if ref_type is not None and (not defn.is_static or defn.name == "__new__"): + arg_index = 1 + if arg_index < len(typ.arg_types) and not is_subtype( + typ.type_is, typ.arg_types[arg_index] + ): + self.fail( + message_registry.NARROWED_TYPE_NOT_SUBTYPE.format( + format_type(typ.type_is, self.options), + format_type(typ.arg_types[arg_index], self.options), + ), + item, + ) + # Store argument types. for i in range(len(typ.arg_types)): arg_type = typ.arg_types[i] @@ -2178,6 +2194,8 @@ def check_override( elif isinstance(original, CallableType) and isinstance(override, CallableType): if original.type_guard is not None and override.type_guard is None: fail = True + if original.type_is is not None and override.type_is is None: + fail = True if is_private(name): fail = False @@ -5643,7 +5661,7 @@ def combine_maps(list_maps: list[TypeMap]) -> TypeMap: def find_isinstance_check(self, node: Expression) -> tuple[TypeMap, TypeMap]: """Find any isinstance checks (within a chain of ands). Includes implicit and explicit checks for None and calls to callable. - Also includes TypeGuard functions. + Also includes TypeGuard and TypeIs functions. Return value is a map of variables to their types if the condition is true and a map of variables to their types if the condition is false. @@ -5695,7 +5713,7 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1: return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0]) elif isinstance(node.callee, RefExpr): - if node.callee.type_guard is not None: + if node.callee.type_guard is not None or node.callee.type_is is not None: # TODO: Follow *args, **kwargs if node.arg_kinds[0] != nodes.ARG_POS: # the first argument might be used as a kwarg @@ -5721,7 +5739,12 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM # we want the idx-th variable to be narrowed expr = collapse_walrus(node.args[idx]) else: - self.fail(message_registry.TYPE_GUARD_POS_ARG_REQUIRED, node) + kind = ( + "guard" if node.callee.type_guard is not None else "narrower" + ) + self.fail( + message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node + ) return {}, {} if literal(expr) == LITERAL_TYPE: # Note: we wrap the target type, so that we can special case later. @@ -5729,7 +5752,18 @@ def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeM # considered "always right" (i.e. even if the types are not overlapping). # Also note that a care must be taken to unwrap this back at read places # where we use this to narrow down declared type. - return {expr: TypeGuardedType(node.callee.type_guard)}, {} + if node.callee.type_guard is not None: + return {expr: TypeGuardedType(node.callee.type_guard)}, {} + else: + assert node.callee.type_is is not None + return conditional_types_to_typemaps( + expr, + *self.conditional_types_with_intersection( + self.lookup_type(expr), + [TypeRange(node.callee.type_is, is_upper_bound=False)], + expr, + ), + ) elif isinstance(node, ComparisonExpr): # Step 1: Obtain the types of each operand and whether or not we can # narrow their types. (For example, we shouldn't try narrowing the diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index e893410e2b7d..37a90ce55b9e 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -1451,13 +1451,12 @@ def check_call_expr_with_callee_type( object_type=object_type, ) proper_callee = get_proper_type(callee_type) - if ( - isinstance(e.callee, RefExpr) - and isinstance(proper_callee, CallableType) - and proper_callee.type_guard is not None - ): + if isinstance(e.callee, RefExpr) and isinstance(proper_callee, CallableType): # Cache it for find_isinstance_check() - e.callee.type_guard = proper_callee.type_guard + if proper_callee.type_guard is not None: + e.callee.type_guard = proper_callee.type_guard + if proper_callee.type_is is not None: + e.callee.type_is = proper_callee.type_is return ret_type def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type: @@ -5283,7 +5282,7 @@ def infer_lambda_type_using_context( # is a constructor -- but this fallback doesn't make sense for lambdas. callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function")) - if callable_ctx.type_guard is not None: + if callable_ctx.type_guard is not None or callable_ctx.type_is is not None: # Lambda's return type cannot be treated as a `TypeGuard`, # because it is implicit. And `TypeGuard`s must be explicit. # See https://github.com/python/mypy/issues/9927 diff --git a/mypy/constraints.py b/mypy/constraints.py index c4eba2ca1ede..cdfa39ac45f3 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -1018,10 +1018,22 @@ def visit_callable_type(self, template: CallableType) -> list[Constraint]: param_spec = template.param_spec() template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type - if template.type_guard is not None: + if template.type_guard is not None and cactual.type_guard is not None: template_ret_type = template.type_guard - if cactual.type_guard is not None: cactual_ret_type = cactual.type_guard + elif template.type_guard is not None: + template_ret_type = AnyType(TypeOfAny.special_form) + elif cactual.type_guard is not None: + cactual_ret_type = AnyType(TypeOfAny.special_form) + + if template.type_is is not None and cactual.type_is is not None: + template_ret_type = template.type_is + cactual_ret_type = cactual.type_is + elif template.type_is is not None: + template_ret_type = AnyType(TypeOfAny.special_form) + elif cactual.type_is is not None: + cactual_ret_type = AnyType(TypeOfAny.special_form) + res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction)) if param_spec is None: diff --git a/mypy/errorcodes.py b/mypy/errorcodes.py index 72ee63a6a897..688bd6a4ddd5 100644 --- a/mypy/errorcodes.py +++ b/mypy/errorcodes.py @@ -281,5 +281,11 @@ def __hash__(self) -> int: sub_code_of=MISC, ) +NARROWED_TYPE_NOT_SUBTYPE: Final[ErrorCode] = ErrorCode( + "narrowed-type-not-subtype", + "Warn if a TypeIs function's narrowed type is not a subtype of the original type", + "General", +) + # This copy will not include any error codes defined later in the plugins. mypy_error_codes = error_codes.copy() diff --git a/mypy/expandtype.py b/mypy/expandtype.py index 3bf45854b2a0..ec6a2ecfd0d2 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -351,6 +351,7 @@ def visit_callable_type(self, t: CallableType) -> CallableType: arg_names=t.arg_names[:-2] + repl.arg_names, ret_type=t.ret_type.accept(self), type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds), variables=[*repl.variables, *t.variables], ) @@ -384,6 +385,7 @@ def visit_callable_type(self, t: CallableType) -> CallableType: arg_types=arg_types, ret_type=t.ret_type.accept(self), type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), ) if needs_normalization: return expanded.with_normalized_var_args() diff --git a/mypy/fixup.py b/mypy/fixup.py index 02c6ab93f29e..849a6483d724 100644 --- a/mypy/fixup.py +++ b/mypy/fixup.py @@ -270,6 +270,8 @@ def visit_callable_type(self, ct: CallableType) -> None: arg.accept(self) if ct.type_guard is not None: ct.type_guard.accept(self) + if ct.type_is is not None: + ct.type_is.accept(self) def visit_overloaded(self, t: Overloaded) -> None: for ct in t.items: diff --git a/mypy/message_registry.py b/mypy/message_registry.py index fb430b63c74b..ccc1443dacf0 100644 --- a/mypy/message_registry.py +++ b/mypy/message_registry.py @@ -262,7 +262,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage: CONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage("Contiguous iterable with same type expected") ITERABLE_TYPE_EXPECTED: Final = ErrorMessage("Invalid type '{}' for *expr (iterable expected)") -TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type guard requires positional argument") +TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type {} requires positional argument") # Match Statement MISSING_MATCH_ARGS: Final = 'Class "{}" doesn\'t define "__match_args__"' @@ -324,3 +324,6 @@ def with_additional_msg(self, info: str) -> ErrorMessage: ARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage( "Expected string literal for argument name, got {}", codes.SYNTAX ) +NARROWED_TYPE_NOT_SUBTYPE: Final = ErrorMessage( + "Narrowed type {} is not a subtype of input type {}", codes.NARROWED_TYPE_NOT_SUBTYPE +) diff --git a/mypy/messages.py b/mypy/messages.py index db6c91ba9008..92b57ef781a2 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2643,6 +2643,8 @@ def format_literal_value(typ: LiteralType) -> str: elif isinstance(func, CallableType): if func.type_guard is not None: return_type = f"TypeGuard[{format(func.type_guard)}]" + elif func.type_is is not None: + return_type = f"TypeIs[{format(func.type_is)}]" else: return_type = format(func.ret_type) if func.is_ellipsis_args: @@ -2859,6 +2861,8 @@ def [T <: int] f(self, x: int, y: T) -> None s += " -> " if tp.type_guard is not None: s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]" + elif tp.type_is is not None: + s += f"TypeIs[{format_type_bare(tp.type_is, options)}]" else: s += format_type_bare(tp.ret_type, options) diff --git a/mypy/nodes.py b/mypy/nodes.py index 1c781320580a..bb278d92392d 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -1755,6 +1755,7 @@ class RefExpr(Expression): "is_inferred_def", "is_alias_rvalue", "type_guard", + "type_is", ) def __init__(self) -> None: @@ -1776,6 +1777,8 @@ def __init__(self) -> None: self.is_alias_rvalue = False # Cache type guard from callable_type.type_guard self.type_guard: mypy.types.Type | None = None + # And same for TypeIs + self.type_is: mypy.types.Type | None = None @property def fullname(self) -> str: diff --git a/mypy/semanal.py b/mypy/semanal.py index 38d5ddec0818..6bf02382a036 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -881,6 +881,13 @@ def analyze_func_def(self, defn: FuncDef) -> None: ) # in this case, we just kind of just ... remove the type guard. result = result.copy_modified(type_guard=None) + if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + '"TypeIs" functions must have a positional argument', + result, + code=codes.VALID_TYPE, + ) + result = result.copy_modified(type_is=None) result = self.remove_unpack_kwargs(defn, result) if has_self_type and self.type is not None: diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 2d536f892a2a..4d5e7335b14f 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -683,10 +683,23 @@ def visit_callable_type(self, left: CallableType) -> bool: if left.type_guard is not None and right.type_guard is not None: if not self._is_subtype(left.type_guard, right.type_guard): return False + elif left.type_is is not None and right.type_is is not None: + # For TypeIs we have to check both ways; it is unsafe to pass + # a TypeIs[Child] when a TypeIs[Parent] is expected, because + # if the narrower returns False, we assume that the narrowed value is + # *not* a Parent. + if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype( + right.type_is, left.type_is + ): + return False elif right.type_guard is not None and left.type_guard is None: # This means that one function has `TypeGuard` and other does not. # They are not compatible. See https://github.com/python/mypy/issues/11307 return False + elif right.type_is is not None and left.type_is is None: + # Similarly, if one function has `TypeIs` and the other does not, + # they are not compatible. + return False return is_callable_compatible( left, right, diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 9cc0114df333..8a9ac8f4ac31 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -668,7 +668,10 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ ) return AnyType(TypeOfAny.from_error) return RequiredType(self.anal_type(t.args[0]), required=False) - elif self.anal_type_guard_arg(t, fullname) is not None: + elif ( + self.anal_type_guard_arg(t, fullname) is not None + or self.anal_type_is_arg(t, fullname) is not None + ): # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args) return self.named_type("builtins.bool") elif fullname in ("typing.Unpack", "typing_extensions.Unpack"): @@ -986,7 +989,8 @@ def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type: variables = t.variables else: variables, _ = self.bind_function_type_variables(t, t) - special = self.anal_type_guard(t.ret_type) + type_guard = self.anal_type_guard(t.ret_type) + type_is = self.anal_type_is(t.ret_type) arg_kinds = t.arg_kinds if len(arg_kinds) >= 2 and arg_kinds[-2] == ARG_STAR and arg_kinds[-1] == ARG_STAR2: arg_types = self.anal_array(t.arg_types[:-2], nested=nested) + [ @@ -1041,7 +1045,8 @@ def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type: # its type will be the falsey FakeInfo fallback=(t.fallback if t.fallback.type else self.named_type("builtins.function")), variables=self.anal_var_defs(variables), - type_guard=special, + type_guard=type_guard, + type_is=type_is, unpack_kwargs=unpacked_kwargs, ) return ret @@ -1064,6 +1069,22 @@ def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None: return self.anal_type(t.args[0]) return None + def anal_type_is(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_is_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeIs", "typing.TypeIs"): + if len(t.args) != 1: + self.fail("TypeIs must have exactly one type argument", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> Type: """Analyze signature argument type for *args and **kwargs argument.""" if isinstance(t, UnboundType) and t.name and "." in t.name and not t.args: diff --git a/mypy/types.py b/mypy/types.py index f76e35784d8f..b34efde15b31 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -1800,6 +1800,7 @@ class CallableType(FunctionLike): "def_extras", # Information about original definition we want to serialize. # This is used for more detailed error messages. "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case). + "type_is", # T, if -> TypeIs[T] (ret_type is bool in this case). "from_concatenate", # whether this callable is from a concatenate object # (this is used for error messages) "imprecise_arg_kinds", @@ -1826,6 +1827,7 @@ def __init__( bound_args: Sequence[Type | None] = (), def_extras: dict[str, Any] | None = None, type_guard: Type | None = None, + type_is: Type | None = None, from_concatenate: bool = False, imprecise_arg_kinds: bool = False, unpack_kwargs: bool = False, @@ -1875,6 +1877,7 @@ def __init__( else: self.def_extras = {} self.type_guard = type_guard + self.type_is = type_is self.unpack_kwargs = unpack_kwargs def copy_modified( @@ -1896,6 +1899,7 @@ def copy_modified( bound_args: Bogus[list[Type | None]] = _dummy, def_extras: Bogus[dict[str, Any]] = _dummy, type_guard: Bogus[Type | None] = _dummy, + type_is: Bogus[Type | None] = _dummy, from_concatenate: Bogus[bool] = _dummy, imprecise_arg_kinds: Bogus[bool] = _dummy, unpack_kwargs: Bogus[bool] = _dummy, @@ -1920,6 +1924,7 @@ def copy_modified( bound_args=bound_args if bound_args is not _dummy else self.bound_args, def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras), type_guard=type_guard if type_guard is not _dummy else self.type_guard, + type_is=type_is if type_is is not _dummy else self.type_is, from_concatenate=( from_concatenate if from_concatenate is not _dummy else self.from_concatenate ), @@ -2233,6 +2238,7 @@ def serialize(self) -> JsonDict: "bound_args": [(None if t is None else t.serialize()) for t in self.bound_args], "def_extras": dict(self.def_extras), "type_guard": self.type_guard.serialize() if self.type_guard is not None else None, + "type_is": (self.type_is.serialize() if self.type_is is not None else None), "from_concatenate": self.from_concatenate, "imprecise_arg_kinds": self.imprecise_arg_kinds, "unpack_kwargs": self.unpack_kwargs, @@ -2257,6 +2263,7 @@ def deserialize(cls, data: JsonDict) -> CallableType: type_guard=( deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None ), + type_is=(deserialize_type(data["type_is"]) if data["type_is"] is not None else None), from_concatenate=data["from_concatenate"], imprecise_arg_kinds=data["imprecise_arg_kinds"], unpack_kwargs=data["unpack_kwargs"], @@ -3315,6 +3322,8 @@ def visit_callable_type(self, t: CallableType) -> str: if not isinstance(get_proper_type(t.ret_type), NoneType): if t.type_guard is not None: s += f" -> TypeGuard[{t.type_guard.accept(self)}]" + elif t.type_is is not None: + s += f" -> TypeIs[{t.type_is.accept(self)}]" else: s += f" -> {t.ret_type.accept(self)}" diff --git a/test-data/unit/check-errorcodes.test b/test-data/unit/check-errorcodes.test index 7f5f05d37595..9d49480539e0 100644 --- a/test-data/unit/check-errorcodes.test +++ b/test-data/unit/check-errorcodes.test @@ -1182,3 +1182,11 @@ class D(C): def other(self) -> None: self.bad2: int = 5 # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] [builtins fixtures/property.pyi] + +[case testNarrowedTypeNotSubtype] +from typing_extensions import TypeIs + +def f(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" [narrowed-type-not-subtype] + pass + +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-typeguard.test b/test-data/unit/check-typeguard.test index c48887bb016a..66c21bf3abe1 100644 --- a/test-data/unit/check-typeguard.test +++ b/test-data/unit/check-typeguard.test @@ -504,7 +504,7 @@ def with_bool(o: object) -> bool: pass accepts_typeguard(with_bool_typeguard) accepts_typeguard(with_str_typeguard) -accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[bool]]" +accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[Never]]" [builtins fixtures/tuple.pyi] [case testTypeGuardAsOverloadedFunctionArg] diff --git a/test-data/unit/check-typeis.test b/test-data/unit/check-typeis.test new file mode 100644 index 000000000000..04b64a45c8c1 --- /dev/null +++ b/test-data/unit/check-typeis.test @@ -0,0 +1,798 @@ +[case testTypeIsBasic] +from typing_extensions import TypeIs +class Point: pass +def is_point(a: object) -> TypeIs[Point]: pass +def main(a: object) -> None: + if is_point(a): + reveal_type(a) # N: Revealed type is "__main__.Point" + else: + reveal_type(a) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsElif] +from typing_extensions import TypeIs +from typing import Union +class Point: pass +def is_point(a: object) -> TypeIs[Point]: pass +class Line: pass +def is_line(a: object) -> TypeIs[Line]: pass +def main(a: Union[Point, Line, int]) -> None: + if is_point(a): + reveal_type(a) # N: Revealed type is "__main__.Point" + elif is_line(a): + reveal_type(a) # N: Revealed type is "__main__.Line" + else: + reveal_type(a) # N: Revealed type is "builtins.int" + +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgsNone] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs: # E: TypeIs must have exactly one type argument + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgsTooMany] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[int, int]: # E: TypeIs must have exactly one type argument + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsTypeArgType] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[42]: # E: Invalid type: try using Literal[42] instead? + pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsRepr] +from typing_extensions import TypeIs +def foo(a: object) -> TypeIs[int]: + pass +reveal_type(foo) # N: Revealed type is "def (a: builtins.object) -> TypeIs[builtins.int]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsCallArgsNone] +from typing_extensions import TypeIs +class Point: pass + +def is_point() -> TypeIs[Point]: pass # E: "TypeIs" functions must have a positional argument +def main(a: object) -> None: + if is_point(): + reveal_type(a) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsCallArgsMultiple] +from typing_extensions import TypeIs +class Point: pass +def is_point(a: object, b: object) -> TypeIs[Point]: pass +def main(a: object, b: object) -> None: + if is_point(a, b): + reveal_type(a) # N: Revealed type is "__main__.Point" + reveal_type(b) # N: Revealed type is "builtins.object" +[builtins fixtures/tuple.pyi] + +[case testTypeIsIsBool] +from typing_extensions import TypeIs +def f(a: TypeIs[int]) -> None: pass +reveal_type(f) # N: Revealed type is "def (a: builtins.bool)" +a: TypeIs[int] +reveal_type(a) # N: Revealed type is "builtins.bool" +class C: + a: TypeIs[int] +reveal_type(C().a) # N: Revealed type is "builtins.bool" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithTypeVar] +from typing import TypeVar, Tuple, Type +from typing_extensions import TypeIs +T = TypeVar('T') +def is_tuple_of_type(a: Tuple[object, ...], typ: Type[T]) -> TypeIs[Tuple[T, ...]]: pass +def main(a: Tuple[object, ...]): + if is_tuple_of_type(a, int): + reveal_type(a) # N: Revealed type is "builtins.tuple[builtins.int, ...]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsUnionIn] +from typing import Union +from typing_extensions import TypeIs +def is_foo(a: Union[int, str]) -> TypeIs[str]: pass +def main(a: Union[str, int]) -> None: + if is_foo(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" + reveal_type(a) # N: Revealed type is "Union[builtins.str, builtins.int]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsUnionOut] +from typing import Union +from typing_extensions import TypeIs +def is_foo(a: object) -> TypeIs[Union[int, str]]: pass +def main(a: object) -> None: + if is_foo(a): + reveal_type(a) # N: Revealed type is "Union[builtins.int, builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNonzeroFloat] +from typing_extensions import TypeIs +def is_nonzero(a: object) -> TypeIs[float]: pass +def main(a: int): + if is_nonzero(a): + reveal_type(a) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsHigherOrder] +from typing import Callable, TypeVar, Iterable, List +from typing_extensions import TypeIs +T = TypeVar('T') +R = TypeVar('R') +def filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterable[R]: pass +def is_float(a: object) -> TypeIs[float]: pass +a: List[object] = ["a", 0, 0.0] +b = filter(is_float, a) +reveal_type(b) # N: Revealed type is "typing.Iterable[builtins.float]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMethod] +from typing_extensions import TypeIs +class C: + def main(self, a: object) -> None: + if self.is_float(a): + reveal_type(self) # N: Revealed type is "__main__.C" + reveal_type(a) # N: Revealed type is "builtins.float" + def is_float(self, a: object) -> TypeIs[float]: pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsCrossModule] +import guard +from points import Point +def main(a: object) -> None: + if guard.is_point(a): + reveal_type(a) # N: Revealed type is "points.Point" +[file guard.py] +from typing_extensions import TypeIs +import points +def is_point(a: object) -> TypeIs[points.Point]: pass +[file points.py] +class Point: pass +[builtins fixtures/tuple.pyi] + +[case testTypeIsBodyRequiresBool] +from typing_extensions import TypeIs +def is_float(a: object) -> TypeIs[float]: + return "not a bool" # E: Incompatible return value type (got "str", expected "bool") +[builtins fixtures/tuple.pyi] + +[case testTypeIsNarrowToTypedDict] +from typing import Mapping, TypedDict +from typing_extensions import TypeIs +class User(TypedDict): + name: str + id: int +def is_user(a: Mapping[str, object]) -> TypeIs[User]: + return isinstance(a.get("name"), str) and isinstance(a.get("id"), int) +def main(a: Mapping[str, object]) -> None: + if is_user(a): + reveal_type(a) # N: Revealed type is "TypedDict('__main__.User', {'name': builtins.str, 'id': builtins.int})" +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi] + +[case testTypeIsInAssert] +from typing_extensions import TypeIs +def is_float(a: object) -> TypeIs[float]: pass +def main(a: object) -> None: + assert is_float(a) + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsFromAny] +from typing import Any +from typing_extensions import TypeIs +def is_objfloat(a: object) -> TypeIs[float]: pass +def is_anyfloat(a: Any) -> TypeIs[float]: pass +def objmain(a: object) -> None: + if is_objfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" + if is_anyfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" +def anymain(a: Any) -> None: + if is_objfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" + if is_anyfloat(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNegatedAndElse] +from typing import Union +from typing_extensions import TypeIs +def is_int(a: object) -> TypeIs[int]: pass +def is_str(a: object) -> TypeIs[str]: pass +def intmain(a: Union[int, str]) -> None: + if not is_int(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" +def strmain(a: Union[int, str]) -> None: + if is_str(a): + reveal_type(a) # N: Revealed type is "builtins.str" + else: + reveal_type(a) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsClassMethod] +from typing_extensions import TypeIs +class C: + @classmethod + def is_float(cls, a: object) -> TypeIs[float]: pass + def method(self, a: object) -> None: + if self.is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +def main(a: object) -> None: + if C.is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/classmethod.pyi] + +[case testTypeIsRequiresPositionalArgs] +from typing_extensions import TypeIs +def is_float(a: object, b: object = 0) -> TypeIs[float]: pass +def main1(a: object) -> None: + if is_float(a=a, b=1): + reveal_type(a) # N: Revealed type is "builtins.float" + + if is_float(b=1, a=a): + reveal_type(a) # N: Revealed type is "builtins.float" + +[builtins fixtures/tuple.pyi] + +[case testTypeIsOverload] +from typing import overload, Any, Callable, Iterable, Iterator, List, Optional, TypeVar +from typing_extensions import TypeIs + +T = TypeVar("T") +R = TypeVar("R") + +@overload +def filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterator[R]: ... +@overload +def filter(f: Callable[[T], bool], it: Iterable[T]) -> Iterator[T]: ... +def filter(*args): pass + +def is_int_typeis(a: object) -> TypeIs[int]: pass +def is_int_bool(a: object) -> bool: pass + +def main(a: List[Optional[int]]) -> None: + bb = filter(lambda x: x is not None, a) + reveal_type(bb) # N: Revealed type is "typing.Iterator[Union[builtins.int, None]]" + # Also, if you replace 'bool' with 'Any' in the second overload, bb is Iterator[Any] + cc = filter(is_int_typeis, a) + reveal_type(cc) # N: Revealed type is "typing.Iterator[builtins.int]" + dd = filter(is_int_bool, a) + reveal_type(dd) # N: Revealed type is "typing.Iterator[Union[builtins.int, None]]" + +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi] + +[case testTypeIsDecorated] +from typing import TypeVar +from typing_extensions import TypeIs +T = TypeVar("T") +def decorator(f: T) -> T: pass +@decorator +def is_float(a: object) -> TypeIs[float]: + pass +def main(a: object) -> None: + if is_float(a): + reveal_type(a) # N: Revealed type is "builtins.float" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMethodOverride] +from typing_extensions import TypeIs +class C: + def is_float(self, a: object) -> TypeIs[float]: pass +class D(C): + def is_float(self, a: object) -> bool: pass # Fail +[builtins fixtures/tuple.pyi] +[out] +main:5: error: Signature of "is_float" incompatible with supertype "C" +main:5: note: Superclass: +main:5: note: def is_float(self, a: object) -> TypeIs[float] +main:5: note: Subclass: +main:5: note: def is_float(self, a: object) -> bool + +[case testTypeIsInAnd] +from typing import Any +from typing_extensions import TypeIs +def isclass(a: object) -> bool: + pass +def isfloat(a: object) -> TypeIs[float]: + pass +def isstr(a: object) -> TypeIs[str]: + pass + +def coverage1(obj: Any) -> bool: + if isfloat(obj) and obj.__self__ is not None and isclass(obj.__self__): # E: "float" has no attribute "__self__" + reveal_type(obj) # N: Revealed type is "builtins.float" + return True + reveal_type(obj) # N: Revealed type is "Any" + return False + +def coverage2(obj: Any) -> bool: + if not (isfloat(obj) or isstr(obj)): + reveal_type(obj) # N: Revealed type is "Any" + return True + reveal_type(obj) # N: Revealed type is "Union[builtins.float, builtins.str]" + return False +[builtins fixtures/classmethod.pyi] + +[case testAssignToTypeIsedVariable1] +from typing_extensions import TypeIs + +class A: pass +class B(A): pass + +def guard(a: A) -> TypeIs[B]: + pass + +a = A() +if not guard(a): + a = A() +[builtins fixtures/tuple.pyi] + +[case testAssignToTypeIsedVariable2] +from typing_extensions import TypeIs + +class A: pass +class B: pass + +def guard(a: object) -> TypeIs[B]: + pass + +a = A() +if not guard(a): + a = A() +[builtins fixtures/tuple.pyi] + +[case testAssignToTypeIsedVariable3] +from typing_extensions import TypeIs + +class A: pass +class B: pass + +def guard(a: object) -> TypeIs[B]: + pass + +a = A() +if guard(a): + reveal_type(a) # N: Revealed type is "__main__." + a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A") + reveal_type(a) # N: Revealed type is "__main__." + a = A() + reveal_type(a) # N: Revealed type is "__main__.A" +reveal_type(a) # N: Revealed type is "__main__.A" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionAny] +from typing_extensions import TypeIs +from typing import Any + +class A: ... +def f(x: object) -> TypeIs[A]: ... +def g(x: object) -> None: ... + +def test(x: Any) -> None: + if not(f(x) or x): + return + g(reveal_type(x)) # N: Revealed type is "Union[__main__.A, Any]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionUnionOther] +from typing_extensions import TypeIs +from typing import Any + +class A: ... +class B: ... +def f(x: object) -> TypeIs[A]: ... +def f2(x: object) -> TypeIs[B]: ... +def g(x: object) -> None: ... + +def test(x: object) -> None: + if not(f(x) or f2(x)): + return + g(reveal_type(x)) # N: Revealed type is "Union[__main__.A, __main__.B]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsComprehensionSubtype] +from typing import List +from typing_extensions import TypeIs + +class Base: ... +class Foo(Base): ... +class Bar(Base): ... + +def is_foo(item: object) -> TypeIs[Foo]: + return isinstance(item, Foo) + +def is_bar(item: object) -> TypeIs[Bar]: + return isinstance(item, Bar) + +def foobar(items: List[object]): + a: List[Base] = [x for x in items if is_foo(x) or is_bar(x)] + b: List[Base] = [x for x in items if is_foo(x)] + c: List[Foo] = [x for x in items if is_foo(x)] + d: List[Bar] = [x for x in items if is_foo(x)] # E: List comprehension has incompatible type List[Foo]; expected List[Bar] +[builtins fixtures/tuple.pyi] + +[case testTypeIsNestedRestrictionUnionIsInstance] +from typing_extensions import TypeIs +from typing import Any, List + +class A: ... +def f(x: List[Any]) -> TypeIs[List[str]]: ... +def g(x: object) -> None: ... + +def test(x: List[Any]) -> None: + if not(f(x) or isinstance(x, A)): + return + g(reveal_type(x)) # N: Revealed type is "Union[builtins.list[builtins.str], __main__.]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMultipleCondition] +from typing_extensions import TypeIs +from typing import Any, List + +class Foo: ... +class Bar: ... + +def is_foo(item: object) -> TypeIs[Foo]: + return isinstance(item, Foo) + +def is_bar(item: object) -> TypeIs[Bar]: + return isinstance(item, Bar) + +def foobar(x: object): + if not isinstance(x, Foo) or not isinstance(x, Bar): + return + reveal_type(x) # N: Revealed type is "__main__." + +def foobar_typeis(x: object): + if not is_foo(x) or not is_bar(x): + return + # Looks like a typo but this is what our unique name generation produces + reveal_type(x) # N: Revealed type is "__main__.1" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsFunctionArgAsBoolSubtype] +from typing import Callable +from typing_extensions import TypeIs + +def accepts_bool(f: Callable[[object], bool]): pass + +def with_bool_typeis(o: object) -> TypeIs[bool]: pass +def with_str_typeis(o: object) -> TypeIs[str]: pass +def with_bool(o: object) -> bool: pass + +accepts_bool(with_bool_typeis) +accepts_bool(with_str_typeis) +accepts_bool(with_bool) +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsFunctionArg] +from typing import Callable +from typing_extensions import TypeIs + +def accepts_typeis(f: Callable[[object], TypeIs[bool]]): pass +def different_typeis(f: Callable[[object], TypeIs[str]]): pass + +def with_typeis(o: object) -> TypeIs[bool]: pass +def with_bool(o: object) -> bool: pass + +accepts_typeis(with_typeis) +accepts_typeis(with_bool) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[bool]]" + +different_typeis(with_typeis) # E: Argument 1 to "different_typeis" has incompatible type "Callable[[object], TypeIs[bool]]"; expected "Callable[[object], TypeIs[str]]" +different_typeis(with_bool) # E: Argument 1 to "different_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[str]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsGenericFunctionArg] +from typing import Callable, TypeVar +from typing_extensions import TypeIs + +T = TypeVar('T') + +def accepts_typeis(f: Callable[[object], TypeIs[T]]): pass + +def with_bool_typeis(o: object) -> TypeIs[bool]: pass +def with_str_typeis(o: object) -> TypeIs[str]: pass +def with_bool(o: object) -> bool: pass + +accepts_typeis(with_bool_typeis) +accepts_typeis(with_str_typeis) +accepts_typeis(with_bool) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeIs[Never]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsAsOverloadedFunctionArg] +# https://github.com/python/mypy/issues/11307 +from typing import Callable, TypeVar, Generic, Any, overload +from typing_extensions import TypeIs + +_T = TypeVar('_T') + +class filter(Generic[_T]): + @overload + def __init__(self, function: Callable[[object], TypeIs[_T]]) -> None: pass + @overload + def __init__(self, function: Callable[[_T], Any]) -> None: pass + def __init__(self, function): pass + +def is_int_typeis(a: object) -> TypeIs[int]: pass +def returns_bool(a: object) -> bool: pass + +reveal_type(filter(is_int_typeis)) # N: Revealed type is "__main__.filter[builtins.int]" +reveal_type(filter(returns_bool)) # N: Revealed type is "__main__.filter[builtins.object]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsSubtypingVariance] +from typing import Callable +from typing_extensions import TypeIs + +class A: pass +class B(A): pass +class C(B): pass + +def accepts_typeis(f: Callable[[object], TypeIs[B]]): pass + +def with_typeis_a(o: object) -> TypeIs[A]: pass +def with_typeis_b(o: object) -> TypeIs[B]: pass +def with_typeis_c(o: object) -> TypeIs[C]: pass + +accepts_typeis(with_typeis_a) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], TypeIs[A]]"; expected "Callable[[object], TypeIs[B]]" +accepts_typeis(with_typeis_b) +accepts_typeis(with_typeis_c) # E: Argument 1 to "accepts_typeis" has incompatible type "Callable[[object], TypeIs[C]]"; expected "Callable[[object], TypeIs[B]]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithIdentityGeneric] +from typing import TypeVar +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def identity(val: _T) -> TypeIs[_T]: + pass + +def func1(name: _T): + reveal_type(name) # N: Revealed type is "_T`-1" + if identity(name): + reveal_type(name) # N: Revealed type is "_T`-1" + +def func2(name: str): + reveal_type(name) # N: Revealed type is "builtins.str" + if identity(name): + reveal_type(name) # N: Revealed type is "builtins.str" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithGenericOnSecondParam] +from typing import TypeVar +from typing_extensions import TypeIs + +_R = TypeVar("_R") + +def guard(val: object, param: _R) -> TypeIs[_R]: + pass + +def func1(name: object): + reveal_type(name) # N: Revealed type is "builtins.object" + if guard(name, name): + reveal_type(name) # N: Revealed type is "builtins.object" + if guard(name, 1): + reveal_type(name) # N: Revealed type is "builtins.int" + +def func2(name: int): + reveal_type(name) # N: Revealed type is "builtins.int" + if guard(name, True): + reveal_type(name) # N: Revealed type is "builtins.bool" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithGenericInstance] +from typing import TypeVar, List, Iterable +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_list_of_str(val: Iterable[_T]) -> TypeIs[List[_T]]: + pass + +def func(name: Iterable[str]): + reveal_type(name) # N: Revealed type is "typing.Iterable[builtins.str]" + if is_list_of_str(name): + reveal_type(name) # N: Revealed type is "builtins.list[builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsWithTupleGeneric] +from typing import TypeVar, Tuple +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_two_element_tuple(val: Tuple[_T, ...]) -> TypeIs[Tuple[_T, _T]]: + pass + +def func(names: Tuple[str, ...]): + reveal_type(names) # N: Revealed type is "builtins.tuple[builtins.str, ...]" + if is_two_element_tuple(names): + reveal_type(names) # N: Revealed type is "Tuple[builtins.str, builtins.str]" +[builtins fixtures/tuple.pyi] + +[case testTypeIsErroneousDefinitionFails] +from typing_extensions import TypeIs + +class Z: + def typeis1(self, *, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + + @staticmethod + def typeis2(x: object) -> TypeIs[int]: + ... + + @staticmethod + def typeis3(*, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + +def bad_typeis(*, x: object) -> TypeIs[int]: # E: "TypeIs" functions must have a positional argument + ... + +[builtins fixtures/classmethod.pyi] + +[case testTypeIsWithKeywordArg] +from typing_extensions import TypeIs + +class Z: + def typeis(self, x: object) -> TypeIs[int]: + ... + +def typeis(x: object) -> TypeIs[int]: + ... + +n: object +if typeis(x=n): + reveal_type(n) # N: Revealed type is "builtins.int" + +if Z().typeis(x=n): + reveal_type(n) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testStaticMethodTypeIs] +from typing_extensions import TypeIs + +class Y: + @staticmethod + def typeis(h: object) -> TypeIs[int]: + ... + +x: object +if Y().typeis(x): + reveal_type(x) # N: Revealed type is "builtins.int" +if Y.typeis(x): + reveal_type(x) # N: Revealed type is "builtins.int" +[builtins fixtures/classmethod.pyi] + +[case testTypeIsKwargFollowingThroughOverloaded] +from typing import overload, Union +from typing_extensions import TypeIs + +@overload +def typeis(x: object, y: str) -> TypeIs[str]: + ... + +@overload +def typeis(x: object, y: int) -> TypeIs[int]: + ... + +def typeis(x: object, y: Union[int, str]) -> Union[TypeIs[int], TypeIs[str]]: + ... + +x: object +if typeis(x=x, y=42): + reveal_type(x) # N: Revealed type is "builtins.int" + +if typeis(y=42, x=x): + reveal_type(x) # N: Revealed type is "builtins.int" + +if typeis(x=x, y="42"): + reveal_type(x) # N: Revealed type is "builtins.str" + +if typeis(y="42", x=x): + reveal_type(x) # N: Revealed type is "builtins.str" +[builtins fixtures/tuple.pyi] + +[case testGenericAliasWithTypeIs] +from typing import Callable, List, TypeVar +from typing_extensions import TypeIs + +T = TypeVar('T') +A = Callable[[object], TypeIs[List[T]]] +def foo(x: object) -> TypeIs[List[str]]: ... + +def test(f: A[T]) -> T: ... +reveal_type(test(foo)) # N: Revealed type is "builtins.str" +[builtins fixtures/list.pyi] + +[case testNoCrashOnDunderCallTypeIs] +from typing_extensions import TypeIs + +class A: + def __call__(self, x) -> TypeIs[int]: + return True + +a: A +assert a(x=1) + +x: object +assert a(x=x) +reveal_type(x) # N: Revealed type is "builtins.int" +[builtins fixtures/tuple.pyi] + +[case testTypeIsMustBeSubtypeFunctions] +from typing_extensions import TypeIs +from typing import List, Sequence, TypeVar + +def f(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + +T = TypeVar('T') + +def g(x: List[T]) -> TypeIs[Sequence[T]]: # E: Narrowed type "Sequence[T]" is not a subtype of input type "List[T]" + pass + +[builtins fixtures/tuple.pyi] + +[case testTypeIsMustBeSubtypeMethods] +from typing_extensions import TypeIs + +class NarrowHolder: + @classmethod + def cls_narrower_good(cls, x: object) -> TypeIs[int]: + pass + + @classmethod + def cls_narrower_bad(cls, x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + @staticmethod + def static_narrower_good(x: object) -> TypeIs[int]: + pass + + @staticmethod + def static_narrower_bad(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + def inst_narrower_good(self, x: object) -> TypeIs[int]: + pass + + def inst_narrower_bad(self, x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" + pass + + +[builtins fixtures/classmethod.pyi] + +[case testTypeIsTypeGuardNoSubtyping] +from typing_extensions import TypeGuard, TypeIs +from typing import Callable + +def accept_typeis(x: Callable[[object], TypeIs[str]]): + pass + +def accept_typeguard(x: Callable[[object], TypeGuard[str]]): + pass + +def typeis(x: object) -> TypeIs[str]: + pass + +def typeguard(x: object) -> TypeGuard[str]: + pass + +accept_typeis(typeis) +accept_typeis(typeguard) # E: Argument 1 to "accept_typeis" has incompatible type "Callable[[object], TypeGuard[str]]"; expected "Callable[[object], TypeIs[str]]" +accept_typeguard(typeis) # E: Argument 1 to "accept_typeguard" has incompatible type "Callable[[object], TypeIs[str]]"; expected "Callable[[object], TypeGuard[str]]" +accept_typeguard(typeguard) + +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/lib-stub/typing_extensions.pyi b/test-data/unit/lib-stub/typing_extensions.pyi index 68dd985cfe2a..18b6c8fc477c 100644 --- a/test-data/unit/lib-stub/typing_extensions.pyi +++ b/test-data/unit/lib-stub/typing_extensions.pyi @@ -34,6 +34,7 @@ Concatenate: _SpecialForm TypeAlias: _SpecialForm TypeGuard: _SpecialForm +TypeIs: _SpecialForm Never: _SpecialForm TypeVarTuple: _SpecialForm