Files

58 KiB

Narrowing for isinstance checks

Narrowing for isinstance(object, classinfo) expressions.

classinfo is a single type

from typing import Literal

def _(x: Literal[1, "a"]):
    if isinstance(x, int):
        reveal_type(x)  # revealed: Literal[1]

    if isinstance(x, str):
        reveal_type(x)  # revealed: Literal["a"]
        if isinstance(x, int):
            reveal_type(x)  # revealed: Never

    if isinstance(x, (int, object)):
        reveal_type(x)  # revealed: Literal[1, "a"]

classinfo is a tuple of types

Note: isinstance(x, (int, str)) should not be confused with isinstance(x, tuple[(int, str)]). The former is equivalent to isinstance(x, int | str):

from typing import Literal

def _(x: Literal[1, "a"], y: Literal[1, "a", b"b"]):
    if isinstance(x, (int, str)):
        reveal_type(x)  # revealed: Literal[1, "a"]
    else:
        reveal_type(x)  # revealed: Never

    if isinstance(x, (int, bytes)):
        reveal_type(x)  # revealed: Literal[1]

    if isinstance(x, (bytes, str)):
        reveal_type(x)  # revealed: Literal["a"]

    # No narrowing should occur if a larger type is also
    # one of the possibilities:
    if isinstance(x, (int, object)):
        reveal_type(x)  # revealed: Literal[1, "a"]
    else:
        reveal_type(x)  # revealed: Never

    if isinstance(y, (int, str)):
        reveal_type(y)  # revealed: Literal[1, "a"]

    if isinstance(y, (int, bytes)):
        reveal_type(y)  # revealed: Literal[1, b"b"]

    if isinstance(y, (str, bytes)):
        reveal_type(y)  # revealed: Literal["a", b"b"]

A tuple of classes covers a recursive union

A fixed tuple of classes can cover every alternative in a recursive union. Such an isinstance check is always true; omitting one of those classes leaves the result uncertain.

[environment]
python-version = "3.12"
Implicit = int | list["Implicit"]
type Explicit = int | list[Explicit]

def implicit(value: Implicit):
    reveal_type(isinstance(value, (int, list)))  # revealed: Literal[True]
    reveal_type(isinstance(value, (int, str)))  # revealed: bool

def explicit(value: Explicit):
    reveal_type(isinstance(value, (int, list)))  # revealed: Literal[True]
    reveal_type(isinstance(value, (int, str)))  # revealed: bool

classinfo is a nested tuple of types

from typing import Literal

def _(x: Literal[1, "a"]):
    if isinstance(x, (bool, (bytes, int))):
        reveal_type(x)  # revealed: Literal[1]
    else:
        reveal_type(x)  # revealed: Literal["a"]

Recursive tuples as classinfo

[environment]
python-version = "3.12"

A recursive tuple of integer classes narrows a successful check to int. An unsuccessful check does not exclude integers: the tuple can be empty or contain only a subclass of int. Implicit and PEP 695 aliases describe the same class-info values.

ClassInfo = type[int] | tuple["ClassInfo", ...]
type ExplicitClassInfo = type[int] | tuple[ExplicitClassInfo, ...]

def implicit(value: object, classes: ClassInfo):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: int
    else:
        reveal_type(value)  # revealed: object

def explicit(value: object, classes: ExplicitClassInfo):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: int
    else:
        reveal_type(value)  # revealed: object

Even when the leaf class is final, a failed check does not exclude its instances: the recursive tuple can be empty.

from typing import final

@final
class Leaf: ...

FinalClasses = type[Leaf] | tuple["FinalClasses", ...]
type ExplicitFinalClasses = type[Leaf] | tuple[ExplicitFinalClasses, ...]

def final_classes(value: object, classes: FinalClasses, explicit_classes: ExplicitFinalClasses):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: Leaf
    else:
        reveal_type(value)  # revealed: object
    if isinstance(value, explicit_classes):
        reveal_type(value)  # revealed: Leaf
    else:
        reveal_type(value)  # revealed: object

A tuple tree with no class objects can only make the check fail:

OnlyTuples = tuple["OnlyTuples", ...]
type ExplicitOnlyTuples = tuple[ExplicitOnlyTuples, ...]

def only_tuples(value: object, classes: OnlyTuples, explicit_classes: ExplicitOnlyTuples):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: Never
    else:
        reveal_type(value)  # revealed: object
    if isinstance(value, explicit_classes):
        reveal_type(value)  # revealed: Never
    else:
        reveal_type(value)  # revealed: object

classinfo with changing recursive arguments

[environment]
python-version = "3.12"

Deeper tuples can contain different classes when the recursive type arguments change. The outer argument int does not describe all the classes tested: (list,) is also a valid class-info value.

from typing import TypeAlias, TypeVar

T = TypeVar("T")
Growing: TypeAlias = type[T] | tuple["Growing[list[T]]", ...]
type ExplicitGrowing[T] = type[T] | tuple[ExplicitGrowing[list[T]], ...]

classes: Growing[int] = (list,)
explicit_classes: ExplicitGrowing[int] = (list,)

def implicit(value: object, classes: Growing[int]):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: object

def explicit(value: object, classes: ExplicitGrowing[int]):
    if isinstance(value, classes):
        reveal_type(value)  # revealed: object

Validating growing recursive tuples

[environment]
python-version = "3.12"

Changing type arguments does not invalidate a recursive tuple whose leaves are always classes. Both isinstance and issubclass accept these tuples, including classes reached through another alias.

from typing import TypeVar

T = TypeVar("T")
type Identity[U] = U
ClassInfo = Identity[type] | tuple["ClassInfo[list[T]]", ...]
type ExplicitClassInfo[T] = Identity[type] | tuple[ExplicitClassInfo[list[T]], ...]

def valid(classes: ClassInfo[int], explicit_classes: ExplicitClassInfo[int]):
    isinstance(None, classes)
    issubclass(int, classes)
    isinstance(None, explicit_classes)
    issubclass(int, explicit_classes)

When the argument also supplies the leaf type, a class at the outer level does not guarantee that all deeper leaves are classes. These aliases also admit lists, which are invalid class-info values.

Invalid = T | tuple["Invalid[list[T]]", ...]
type ExplicitInvalid[T] = T | tuple[ExplicitInvalid[list[T]], ...]

def invalid(classes: Invalid[type], explicit_classes: ExplicitInvalid[type]):
    isinstance(None, classes)  # error: [invalid-argument-type]
    issubclass(int, classes)  # error: [invalid-argument-type]
    isinstance(None, explicit_classes)  # error: [invalid-argument-type]
    issubclass(int, explicit_classes)  # error: [invalid-argument-type]

A leaf can itself be a recursive tuple with fixed arguments. Those arguments still constrain its leaves, even when the enclosing alias has growing arguments.

U = TypeVar("U")
Stable = U | tuple["Stable[U]", ...]
Nested = Stable[type] | tuple["Nested[list[T]]", ...]
type ExplicitNested[T] = Stable[type] | tuple[ExplicitNested[list[T]], ...]

def nested(classes: Nested[int], explicit_classes: ExplicitNested[int]):
    isinstance(None, classes)
    issubclass(int, classes)
    isinstance(None, explicit_classes)
    issubclass(int, explicit_classes)

Recursive tuples with metaclass arguments

[environment]
python-version = "3.12"

Successive metaclasses are still classes. Starting with type[int], these aliases therefore contain only valid class-info values at every depth.

from typing import TypeVar

T = TypeVar("T")
ClassInfo = T | tuple["ClassInfo[type[T]]", ...]
type ExplicitClassInfo[T] = T | tuple[ExplicitClassInfo[type[T]], ...]

def valid(classes: ClassInfo[type[int]], explicit_classes: ExplicitClassInfo[type[int]]):
    isinstance(None, classes)
    issubclass(int, classes)
    isinstance(None, explicit_classes)
    issubclass(int, explicit_classes)

classinfo is a PEP-604 union of types

[environment]
python-version = "3.10"
def _(x: int | str | bytes | memoryview | range):
    if isinstance(x, int | str):
        reveal_type(x)  # revealed: int | str
    elif isinstance(x, bytes | memoryview):
        reveal_type(x)  # revealed: bytes | memoryview[int]
    else:
        reveal_type(x)  # revealed: range

Although isinstance() usually only works if all elements in the UnionType are class objects, at runtime a special exception is made for None so that isinstance(x, int | None) can work:

def _(x: int | str | bytes | range | None):
    if isinstance(x, int | str | None):
        reveal_type(x)  # revealed: int | str | None
    else:
        reveal_type(x)  # revealed: bytes | range

classinfo is an invalid PEP-604 union of types

Except for the None special case mentioned above, narrowing can only take place if all elements in the PEP-604 union are class literals. If any elements are generic aliases or other types, the isinstance() call may fail at runtime, so no narrowing can take place:

[environment]
python-version = "3.10"
from typing import Any, Literal, NamedTuple

def _(x: int | list[int] | bytes):
    # snapshot: invalid-argument-type
    if isinstance(x, list[int] | int):
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
 --> src/mdtest_snippet.py:5:8
  |
5 |     if isinstance(x, list[int] | int):
  |        ^^^^^^^^^^^^^^---------------^
  |                      |
  |                      This `UnionType` instance contains non-class elements
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Element `<class 'list[int]'>` in the union is not a class object

The repeated list[int] appears once in the diagnostic, before Literal[42].

    # snapshot: invalid-argument-type
    elif isinstance(x, list[int] | (Literal[42] | list[int]) | bytes):
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
 --> src/mdtest_snippet.py:8:10
  |
8 |     elif isinstance(x, list[int] | (Literal[42] | list[int]) | bytes):
  |          ^^^^^^^^^^^^^^---------------------------------------------^
  |                        |
  |                        This `UnionType` instance contains non-class elements
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Elements `<class 'list[int]'>` and `<special-form 'Literal[42]'>` in the union are not class objects
    # snapshot: invalid-argument-type
    elif isinstance(x, Any | NamedTuple | list[int]):
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
  --> src/mdtest_snippet.py:11:10
   |
11 |     elif isinstance(x, Any | NamedTuple | list[int]):
   |          ^^^^^^^^^^^^^^----------------------------^
   |                        |
   |                        This `UnionType` instance contains non-class elements
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Element `<special-form 'typing.Any'>` in the union, and 2 more elements, are not class objects
    else:
        reveal_type(x)  # revealed: int | list[int] | bytes

The same validation also applies when an invalid UnionType is nested inside a tuple:

def _(x: int | list[int] | bytes):
    # snapshot: invalid-argument-type
    if isinstance(x, (int, list[int] | bytes)):
        reveal_type(x)  # revealed: int | list[int] | bytes
    else:
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
  --> src/mdtest_snippet.py:17:8
   |
17 |     if isinstance(x, (int, list[int] | bytes)):
   |        ^^^^^^^^^^^^^^^^^^^^-----------------^^
   |                            |
   |                            This `UnionType` instance contains non-class elements
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Element `<class 'list[int]'>` in the union is not a class object

Including nested tuples:

def _(x: int | list[int] | bytes):
    # snapshot: invalid-argument-type
    if isinstance(x, (int, (str, list[int] | bytes))):
        reveal_type(x)  # revealed: int | list[int] | bytes
    else:
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
  --> src/mdtest_snippet.py:23:8
   |
23 |     if isinstance(x, (int, (str, list[int] | bytes))):
   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^^
   |                                  |
   |                                  This `UnionType` instance contains non-class elements
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Element `<class 'list[int]'>` in the union is not a class object

And non-literal tuples:

classes = (int, list[int] | bytes)

def _(x: int | list[int] | bytes):
    # snapshot: invalid-argument-type
    if isinstance(x, classes):
        reveal_type(x)  # revealed: int | list[int] | bytes
    else:
        reveal_type(x)  # revealed: int | list[int] | bytes
error[invalid-argument-type]: Invalid second argument to `isinstance`
  --> src/mdtest_snippet.py:31:8
   |
31 |     if isinstance(x, classes):
   |        ^^^^^^^^^^^^^^^^^^^^^^
info: A `UnionType` instance can only be used as the second argument to `isinstance` if all elements are class objects
info: Element `<class 'list[int]'>` in the union `list[int] | bytes` is not a class object

classinfo is a types.UnionType

Python 3.10 added the ability to use Union[int, str] as the second argument to isinstance():

from typing import Union

IntOrStr = Union[int, str]

reveal_type(IntOrStr)  # revealed: <types.UnionType special-form 'int | str'>

def _(x: int | str | bytes | memoryview | range):
    if isinstance(x, IntOrStr):
        reveal_type(x)  # revealed: int | str
    elif isinstance(x, Union[bytes, memoryview]):
        reveal_type(x)  # revealed: bytes | memoryview[int]
    else:
        reveal_type(x)  # revealed: range

def _(x: int | str | None):
    if isinstance(x, Union[int, None]):
        reveal_type(x)  # revealed: int | None
    else:
        reveal_type(x)  # revealed: str

ListStrOrInt = Union[list[str], int]

def _(x: dict[int, str] | ListStrOrInt):
    # TODO: this should ideally be an error
    if isinstance(x, ListStrOrInt):
        # TODO: this should not be narrowed
        reveal_type(x)  # revealed: list[str] | int

    # TODO: this should ideally be an error
    if isinstance(x, Union[list[str], int]):
        # TODO: this should not be narrowed
        reveal_type(x)  # revealed: list[str] | int

Optional as classinfo

from typing import Optional

def _(x: int | str | None):
    if isinstance(x, Optional[int]):
        reveal_type(x)  # revealed: int | None
    else:
        reveal_type(x)  # revealed: str

classinfo is a typing.py special form

Certain special forms in typing.py are aliases to classes elsewhere in the standard library; these can be used in isinstance() and issubclass() checks. We support narrowing using them:

import typing as t

def f(x: dict[str, int] | list[str], y: object):
    if isinstance(x, t.Dict):
        reveal_type(x)  # revealed: dict[str, int]
    else:
        reveal_type(x)  # revealed: list[str]

    if isinstance(y, t.Callable):
        reveal_type(y)  # revealed: (...) -> Unknown

Class types

class A: ...
class B: ...
class C: ...

x = object()

if isinstance(x, A):
    reveal_type(x)  # revealed: A
    if isinstance(x, B):
        reveal_type(x)  # revealed: A & B
    else:
        reveal_type(x)  # revealed: A & ~B

if isinstance(x, (A, B)):
    reveal_type(x)  # revealed: A | B
elif isinstance(x, (A, C)):
    reveal_type(x)  # revealed: C & ~A & ~B
else:
    reveal_type(x)  # revealed: ~A & ~B & ~C

NewType instances and concrete-base subclasses

A NewType constructor returns its argument unchanged at runtime, and runtime class checks ignore its static tag. The resulting value can therefore still be an instance of a subclass of its concrete base. For example, UserId(True) is valid because bool is a subtype of int, and the returned value remains a bool.

from typing import NewType

class Base: ...
class Child(Base): ...

BrandedBase = NewType("BrandedBase", Base)
UserId = NewType("UserId", int)

UserId(True)

def narrow_branded_subclass(value: BrandedBase) -> None:
    if isinstance(value, Child):
        reveal_type(value)  # revealed: BrandedBase & Child
    else:
        reveal_type(value)  # revealed: BrandedBase & ~Child

def narrow_branded_boolean(value: UserId) -> None:
    if isinstance(value, bool):
        reveal_type(value)  # revealed: UserId & bool
    else:
        reveal_type(value)  # revealed: UserId & ~bool

No narrowing for instances of builtins.type

from typing import Literal

def _(x: Literal[1, "foo"], t: type):
    if isinstance(x, t):
        reveal_type(x)  # revealed: Literal[1, "foo"]

Do not use custom isinstance for narrowing

from typing import Literal

def _(x: Literal[1, "a"]):
    def isinstance(x, t):
        return True

    if isinstance(x, int):
        reveal_type(x)  # revealed: Literal[1, "a"]

Do support narrowing if isinstance is aliased

from typing import Literal

def _(x: Literal[1, "a"]):
    isinstance_alias = isinstance

    if isinstance_alias(x, int):
        reveal_type(x)  # revealed: Literal[1]

Do support narrowing if isinstance is imported

from builtins import isinstance as imported_isinstance
from typing import Literal

def _(x: Literal[1, "a"]):
    if imported_isinstance(x, int):
        reveal_type(x)  # revealed: Literal[1]

Do not narrow if second argument is not a type

from typing import Literal

def _(x: Literal[1, "a"]):
    # error: [invalid-argument-type] "Argument to function `isinstance` is incorrect: Expected `_ClassInfo`, found `Literal["a"]"
    if isinstance(x, "a"):
        reveal_type(x)  # revealed: Literal[1, "a"]

    # error: [invalid-argument-type] "Argument to function `isinstance` is incorrect: Expected `_ClassInfo`, found `Literal["int"]"
    if isinstance(x, "int"):
        reveal_type(x)  # revealed: Literal[1, "a"]

Do not narrow if there are keyword arguments

from typing import Literal

def _(x: Literal[1, "a"]):
    # error: [unknown-argument]
    if isinstance(x, int, foo="bar"):
        reveal_type(x)  # revealed: Literal[1, "a"]

Splatted calls with invalid classinfo

Diagnostics are still emitted for invalid classinfo types when the arguments are splatted:

args = (object(), int | list[str])
isinstance(*args)  # error: [invalid-argument-type]

Generic aliases are not supported as second argument

The classinfo argument cannot be a generic alias:

def _(x: list[str] | list[int] | list[bytes]):
    # TODO: Ideally, this would be an error (requires https://github.com/astral-sh/ty/issues/116)
    if isinstance(x, list[int]):
        # No narrowing here:
        reveal_type(x)  # revealed: list[str] | list[int] | list[bytes]

    # error: [invalid-argument-type] "Invalid second argument to `isinstance`"
    if isinstance(x, list[int] | list[str]):
        # No narrowing here:
        reveal_type(x)  # revealed: list[str] | list[int] | list[bytes]

type[] types are narrowed as well as class-literal types

def _(x: object, y: type[int]):
    if isinstance(x, y):
        reveal_type(x)  # revealed: int

Negative narrowing is not sound in this case, because type[A] includes subclasses of A:

class A: ...
class B: ...

def f(x: A | B, y: type[A]):
    if isinstance(x, y):
        reveal_type(x)  # revealed: A
        return

    reveal_type(x)  # revealed: A | B

Adding a disjoint element to an existing intersection

We used to incorrectly infer Literal booleans for some of these.

from ty_extensions import Not, Intersection, AlwaysTruthy, AlwaysFalsy

class P: ...

def f(
    a: Intersection[P, AlwaysTruthy],
    b: Intersection[P, AlwaysFalsy],
    c: Intersection[P, Not[AlwaysTruthy]],
    d: Intersection[P, Not[AlwaysFalsy]],
):
    if isinstance(a, bool):
        reveal_type(a)  # revealed: Never
    else:
        reveal_type(a)  # revealed: P & AlwaysTruthy

    if isinstance(b, bool):
        reveal_type(b)  # revealed: Never
    else:
        reveal_type(b)  # revealed: P & AlwaysFalsy

    if isinstance(c, bool):
        reveal_type(c)  # revealed: Never
    else:
        reveal_type(c)  # revealed: P & ~AlwaysTruthy

    if isinstance(d, bool):
        reveal_type(d)  # revealed: Never
    else:
        reveal_type(d)  # revealed: P & ~AlwaysFalsy

Narrowing if an object of type Any or Unknown is used as the second argument

In order to preserve the gradual guarantee, we intersect with the type of the second argument if the type of the second argument is a dynamic type:

from typing import Any
from something_unresolvable import SomethingUnknown  # error: [import-not-found]

class Foo: ...

def f(a: Foo, b: Any):
    if isinstance(a, SomethingUnknown):
        reveal_type(a)  # revealed: Foo & Unknown

    if isinstance(a, b):
        reveal_type(a)  # revealed: Foo & Any

Narrowing if an object with an intersection/union/TypeVar type is used as the second argument

If an intersection with only positive members is used as the second argument, and all positive members of the intersection are valid arguments for the second argument to isinstance(), we intersect with each positive member of the intersection:

[environment]
python-version = "3.12"
from typing import Any
from ty_extensions import Intersection

class Foo: ...

class Bar:
    attribute: int

class Baz:
    attribute: str

def f(x: Foo, y: Intersection[type[Bar], type[Baz]], z: type[Any]):
    if isinstance(x, y):
        reveal_type(x)  # revealed: Foo & Bar & Baz

    if isinstance(x, z):
        reveal_type(x)  # revealed: Foo & Any

The same if a union type is used:

def g(x: Foo, y: type[Bar | Baz]):
    if isinstance(x, y):
        reveal_type(x)  # revealed: (Foo & Bar) | (Foo & Baz)

And even if a TypeVar is used, providing it has valid upper bounds/constraints:

from typing import TypeVar

T = TypeVar("T", bound=type[Bar])

def h_old_syntax(x: Foo, y: T) -> T:
    if isinstance(x, y):
        reveal_type(x)  # revealed: Foo & Bar
        reveal_type(x.attribute)  # revealed: int

    return y

def h[U: type[Bar | Baz]](x: Foo, y: U) -> U:
    if isinstance(x, y):
        reveal_type(x)  # revealed: (Foo & Bar) | (Foo & Baz)
        reveal_type(x.attribute)  # revealed: int | str

    return y

Or even a tuple of tuple of typevars that have intersection bounds...

from ty_extensions import Intersection

class Spam: ...
class Eggs: ...
class Ham: ...
class Mushrooms: ...

def i[T: Intersection[type[Bar], type[Baz | Spam]], U: (type[Eggs], type[Ham])](x: Foo, y: T, z: U) -> tuple[T, U]:
    if isinstance(x, (y, (z, Mushrooms))):
        reveal_type(x)  # revealed: (Foo & Bar & Baz) | (Foo & Bar & Spam) | (Foo & Eggs) | (Foo & Ham) | (Foo & Mushrooms)

    return (y, z)

If some (but not all) positive members of the intersection are not valid isinstance() targets -- for example a parametrized generic alias such as type[list[int]], which raises TypeError at runtime -- we skip those members and narrow using the remaining valid ones, rather than declining to narrow at all:

from ty_extensions import Intersection

def f(x: Foo, y: Intersection[type[Bar], type[list[int]]]):
    if isinstance(x, y):
        # `type[list[int]]` is not a valid `isinstance()` target and contributes no
        # constraint, but `type[Bar]` still narrows.
        reveal_type(x)  # revealed: Foo & Bar
        reveal_type(x.attribute)  # revealed: int

Truthiness checks on a tuple of classes

A truthiness check on the tuple preserves its element type for a subsequent isinstance() check.

def narrow(exc: BaseException, classes: tuple[type[ValueError], ...]) -> ValueError | None:
    assert classes
    if isinstance(exc, classes):
        return exc
    return None

Narrowing after excluding a tuple subclass

Ruling out a tuple subclass preserves the element type for a subsequent isinstance() check. If the check fails, the tuple could be empty, so the subject can still be a bool.

class Special(tuple[type[bool], ...]): ...

def exclude_tuple_subclass(value: object, classes: tuple[type[bool], ...]):
    if isinstance(classes, Special):
        return
    if isinstance(value, classes):
        reveal_type(value)  # revealed: bool
    else:
        reveal_type(value)  # revealed: object

Narrowing with generics

Strict mode

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = true

In strict mode, narrowing to a generic class using isinstance() uses the top materialization of the generic. With a covariant generic, this is equivalent to using the upper bound of the type parameter (by default, object):

from typing import Self

class Covariant[T]:
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, Covariant):
        reveal_type(x)  # revealed: Covariant[object]
        reveal_type(x.get())  # revealed: object

A bounded covariant generic uses its declared upper bound rather than object:

class BoundedCovariant[T: int]:
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, BoundedCovariant):
        reveal_type(x)  # revealed: BoundedCovariant[int]
        reveal_type(x.get())  # revealed: int

Negative narrowing must exclude every specialization of a bounded generic, including a gradual one.

from typing import Any

def excludes_bounded_generic(value: BoundedCovariant[Any] | bool) -> bool:
    if isinstance(value, BoundedCovariant):
        reveal_type(value)  # revealed: BoundedCovariant[int & Any]
        return False

    reveal_type(value)  # revealed: bool
    return value

The same exclusion applies when the generic appears in a tuple of runtime classes.

def excludes_bounded_generic_tuple(
    value: BoundedCovariant[Any] | bool | bytes,
) -> bool:
    if isinstance(value, (BoundedCovariant, bytes)):
        reveal_type(value)  # revealed: BoundedCovariant[int & Any] | bytes
        return False

    reveal_type(value)  # revealed: bool
    return value

Constrained type parameters preserve the materialization of the generic class while making the union of valid constraints available when reading a covariant attribute:

class ConstrainedCovariant[T: (int, str)]:
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, ConstrainedCovariant):
        reveal_type(x)  # revealed: Top[ConstrainedCovariant[Unknown]]
        reveal_type(x.get())  # revealed: int | str

Constrained generics must also be excluded by negative narrowing.

def excludes_constrained_generic(value: ConstrainedCovariant[Any] | bool) -> bool:
    if isinstance(value, ConstrainedCovariant):
        reveal_type(value)  # revealed: ConstrainedCovariant[Any]
        return False

    reveal_type(value)  # revealed: bool
    return value

A concrete ParamSpec specialization does not affect an isinstance() check. Negative narrowing therefore excludes that specialization along with every other instance of the generic class.

from typing import Callable

class ParamSpecBox[**P]:
    callback: Callable[P, None]

def excludes_paramspec_generic(value: ParamSpecBox[[int]] | int) -> int:
    if isinstance(value, ParamSpecBox):
        return 0
    return value

Similarly, contravariant type parameters use their lower bound of Never:

class Contravariant[T]:
    def push(self, x: T) -> None: ...

def _(x: object):
    if isinstance(x, Contravariant):
        reveal_type(x)  # revealed: Contravariant[Never]
        # error: [invalid-argument-type] "Argument to bound method `Contravariant.push` is incorrect: Expected `Never`, found `Literal[42]`"
        x.push(42)

The same applies when the contravariant type parameter appears inside type[T]:

from typing import Generic, TypeVar

T = TypeVar("T", contravariant=True)

class ContravariantType(Generic[T]):
    def push(self, x: type[T]) -> None: ...

def _(x: object):
    if isinstance(x, ContravariantType):
        reveal_type(x)  # revealed: ContravariantType[Never]
        # error: [invalid-argument-type]
        x.push(str)

Invariant generics are trickiest. The top materialization, conceptually the type that includes all instances of the generic class regardless of the type parameter, cannot be represented directly in the type system, so we represent it with the internal Top[] special form.

class Invariant[T]:
    def push(self, x: T) -> None: ...
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, Invariant):
        reveal_type(x)  # revealed: Top[Invariant[Unknown]]
        reveal_type(x.get())  # revealed: object
        # error: [invalid-argument-type] "Argument to bound method `Invariant.push` is incorrect: Expected `Never`, found `Literal[42]`"
        x.push(42)

When reading attributes from a top-materialized generic, only type parameters should be materialized. Unrelated gradual attribute types should be preserved.

from typing import Any

class InvariantWithAny[T: int]:
    a: T
    b: Any

def _(x: object):
    if isinstance(x, InvariantWithAny):
        reveal_type(x)  # revealed: Top[InvariantWithAny[Unknown]]
        reveal_type(x.a)  # revealed: int
        reveal_type(x.b)  # revealed: Any

The same applies in contravariant positions: Any in a parameter type that isn't tied to the generic parameter should not be materialized.

from typing import Any

class ContravariantWithAny[T]:
    def push(self, x: T, y: Any) -> None: ...

def _(x: object):
    if isinstance(x, ContravariantWithAny):
        reveal_type(x)  # revealed: ContravariantWithAny[Never]
        # error: [invalid-argument-type] "Argument to bound method `ContravariantWithAny.push` is incorrect: Expected `Never`, found `Literal[42]`"
        x.push(42, "hello")

When more complex types are involved, the Top[] type may get simplified away.

def _(x: list[int] | set[str]):
    if isinstance(x, list):
        reveal_type(x)  # revealed: list[int]
    else:
        reveal_type(x)  # revealed: set[str]

Though if the types involved are not disjoint bases, we necessarily keep a more complex type.

def _(x: Invariant[int] | Covariant[str]):
    if isinstance(x, Invariant):
        reveal_type(x)  # revealed: Invariant[int] | (Covariant[str] & Top[Invariant[Unknown]])
    else:
        reveal_type(x)  # revealed: Covariant[str] & ~Top[Invariant[Unknown]]

The built-in tuple stores its variable-length shape separately from its generic type argument. Narrowing must preserve and materialize that shape.

def narrow_tuple(value: object) -> None:
    if isinstance(value, tuple):
        reveal_type(value)  # revealed: tuple[object, ...]

A tuple subclass retains its nominal type and inherits its tuple shape from its specialized base. The subclass's own type parameter is still materialized using its declared bound.

class BoundedTuple[T: int](tuple[T, str]): ...

def narrow_tuple_subclass(value: object) -> None:
    if isinstance(value, BoundedTuple):
        reveal_type(value)  # revealed: BoundedTuple[int]
        reveal_type(value[0])  # revealed: int
        reveal_type(value[1])  # revealed: str

The behavior of issubclass() is similar.

def _(x: type[object], y: type[object], z: type[object]):
    if issubclass(x, Covariant):
        reveal_type(x)  # revealed: type[Covariant[object]]
    if issubclass(y, Contravariant):
        reveal_type(y)  # revealed: type[Contravariant[Never]]
    if issubclass(z, Invariant):
        reveal_type(z)  # revealed: type[Top[Invariant[Unknown]]]

Negative issubclass() narrowing also excludes every specialization of a bounded generic.

def excludes_bounded_generic_subclass(
    cls: type[BoundedCovariant[Any]] | type[bool],
) -> type[bool]:
    if issubclass(cls, BoundedCovariant):
        reveal_type(cls)  # revealed: type[BoundedCovariant[Any]]
        return bool

    reveal_type(cls)  # revealed: <class 'bool'>
    return cls

Gradual mode

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = false

In gradual mode, narrowing to a generic class using isinstance() preserves any compatible specialization from the original type. If the original type does not provide a specialization, we intersect with the Unknown specialization. The negative branch still excludes the top materialization because a failed isinstance() check rules out every specialization of the class.

class Covariant[T]:
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, Covariant):
        # `object & Covariant[Unknown]` simplifies to `Covariant[Unknown]`.
        reveal_type(x)  # revealed: Covariant[Unknown]
        reveal_type(x.get())  # revealed: Unknown
    else:
        reveal_type(x)  # revealed: ~Covariant[object]

For contravariant generics, we similarly intersect with the Unknown specialization:

class Contravariant[T]:
    def push(self, x: T) -> None: ...

def _(x: object):
    if isinstance(x, Contravariant):
        reveal_type(x)  # revealed: Contravariant[Unknown]
        x.push(42)
        x.push("foo")
    else:
        reveal_type(x)  # revealed: ~Contravariant[Never]

Similarly, for invariant generics we intersect with the Unknown specialization. Reading produces Unknown, while writing accepts arguments of any type:

class Invariant[T]:
    def push(self, x: T) -> None: ...
    def get(self) -> T:
        raise NotImplementedError

def _(x: object):
    if isinstance(x, Invariant):
        reveal_type(x)  # revealed: Invariant[Unknown]
        reveal_type(x.get)  # revealed: bound method Invariant[Unknown].get() -> Unknown
        reveal_type(x.get())  # revealed: Unknown
        reveal_type(x.push)  # revealed: bound method Invariant[Unknown].push(x: Unknown) -> None
        x.push(42)
        x.push("foo")
    else:
        reveal_type(x)  # revealed: ~Top[Invariant[Unknown]]

Narrowing already specialized generics preserves their concrete type arguments:

class P: ...

def _(x: Covariant[P], y: Contravariant[P], z: Invariant[P]):
    if isinstance(x, Covariant):
        reveal_type(x)  # revealed: Covariant[P]
    if isinstance(y, Contravariant):
        reveal_type(y)  # revealed: Contravariant[P]
    if isinstance(z, Invariant):
        reveal_type(z)  # revealed: Invariant[P]

Specialized base classes also determine the type arguments of matching subclasses, including subclasses with a stricter variance:

class SubOfCovariant[T](Covariant[T]): ...
class SubOfContravariant[T](Contravariant[T]): ...
class SubOfInvariant[T](Invariant[T]): ...

class InvariantSubOfCovariant[T](Covariant[T]):
    def push(self, value: T) -> None: ...

class InvariantSubOfContravariant[T](Contravariant[T]):
    def get(self) -> T:
        raise NotImplementedError

def narrow_generic_subclasses(covariant: Covariant[P], contravariant: Contravariant[P], invariant: Invariant[P]) -> None:
    if isinstance(covariant, SubOfCovariant):
        reveal_type(covariant)  # revealed: SubOfCovariant[P]

    if isinstance(contravariant, SubOfContravariant):
        reveal_type(contravariant)  # revealed: SubOfContravariant[P]

    if isinstance(invariant, SubOfInvariant):
        reveal_type(invariant)  # revealed: SubOfInvariant[P]

    if isinstance(covariant, InvariantSubOfCovariant):
        reveal_type(covariant)  # revealed: InvariantSubOfCovariant[P]

    if isinstance(contravariant, InvariantSubOfContravariant):
        reveal_type(contravariant)  # revealed: InvariantSubOfContravariant[P]

Narrowing unions and intersections preserves unrelated types when they can overlap with the checked class, while excluding unrelated final classes:

from typing import Sequence, final
from ty_extensions import Intersection

@final
class Item: ...

class OpenItem: ...

def _(value: Item | OpenItem | Sequence[int]) -> None:
    if isinstance(value, list):
        reveal_type(value)  # revealed: (OpenItem & list[Unknown]) | list[int]

def _(
    value: Intersection[OpenItem, Sequence[int]],
) -> None:
    if isinstance(value, list):
        reveal_type(value)  # revealed: OpenItem & list[int]

When an intersection contains multiple specialized bases, each base contributes its known type arguments to a matching subclass:

class Left[L]: ...
class Right[R]: ...

class Both[L, R](Left[L], Right[R]):
    left: L
    right: R

def _(value: Intersection[Left[int], Right[str]]) -> None:
    if isinstance(value, Both):
        reveal_type(value)  # revealed: Both[int, str]
        reveal_type(value.left)  # revealed: int
        reveal_type(value.right)  # revealed: str

Subclass type arguments are inferred through their actual inheritance relationship, so this also works correctly if type parameters change position:

class Base[A, B]: ...
class Child[X, Y](Base[Y, X]): ...

def _(value: Base[int, str]) -> None:
    if isinstance(value, Child):
        reveal_type(value)  # revealed: Child[str, int]

A subclass type parameter that cannot be inferred from its base remains Unknown:

class PartiallyInferredChild[Extra1, T, Extra2](Sequence[T]): ...

def _(value: Sequence[int]) -> None:
    if isinstance(value, PartiallyInferredChild):
        reveal_type(value)  # revealed: PartiallyInferredChild[Unknown, int, Unknown]

If we're "narrowing" in the opposite direction, we retain the existing subclass specialization:

def _(covariant: SubOfCovariant[P], contravariant: SubOfContravariant[P], invariant: SubOfInvariant[P]) -> None:
    if isinstance(covariant, Covariant):
        reveal_type(covariant)  # revealed: SubOfCovariant[P]

    if isinstance(contravariant, Contravariant):
        reveal_type(contravariant)  # revealed: SubOfContravariant[P]

    if isinstance(invariant, Invariant):
        reveal_type(invariant)  # revealed: SubOfInvariant[P]

This also works for runtime-checkable protocols:

from typing import Protocol, runtime_checkable

@runtime_checkable
class Reader[T](Protocol):
    def read(self) -> T: ...

class Concrete[T]:
    def read(self) -> T:
        raise NotImplementedError

def _(value: Concrete[int]) -> None:
    if isinstance(value, Reader):
        reveal_type(value)  # revealed: Concrete[int]
        reveal_type(value.read())  # revealed: int

Negative narrowing for protocols with gradual members

Negative narrowing excludes every materialization of a protocol, including when its members are gradual. IntReader is a subtype of the fully materialized Reader protocol, so the negative branch retains only None:

from typing import Any, Protocol, runtime_checkable

@runtime_checkable
class Reader(Protocol):
    def read(self) -> Any: ...

class IntReader:
    def read(self) -> int:
        return 1

def f(reader: IntReader | None):
    if isinstance(reader, Reader):
        reveal_type(reader.read())  # revealed: int
    else:
        reveal_type(reader)  # revealed: None

Narrowing iterables to containers and iterators in strict mode

[analysis]
strict-generic-narrowing = true

Narrowing an Iterable[T] to an Iterator, or to a container type, retains its element type. See generics/set_theoretic.md for more details on the assumptions behind this, and for an explanation of the behavior of invariant containers:

from typing import Iterable, Iterator

def f(values: Iterable[int]):
    if isinstance(values, Iterator):
        reveal_type(values)  # revealed: Iterator[int]
        reveal_type(next(values))  # revealed: int
    if isinstance(values, tuple):
        reveal_type(values)  # revealed: tuple[int, ...]
        reveal_type(values[0])  # revealed: int
    if isinstance(values, frozenset):
        reveal_type(values)  # revealed: frozenset[int]
        reveal_type(next(iter(values)))  # revealed: int
    if isinstance(values, list):
        reveal_type(values)  # revealed: Top[list[Unknown & int]]
        reveal_type(values[0])  # revealed: int
    if isinstance(values, set):
        reveal_type(values)  # revealed: Top[set[Unknown & int]]
        reveal_type(next(iter(values)))  # revealed: int

Use cases: isinstance narrowing and generics

Strict mode

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = true

Covariance

Narrowing from object via isinstance(.., Sequence):

from typing import Sequence, final

def _(xs: object):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: Sequence[object]
        for x in xs:
            reveal_type(x)  # revealed: object
    else:
        reveal_type(xs)  # revealed: ~Sequence[object]

Narrowing from Item | Sequence[Item] via isinstance(.., Sequence):

@final
class Item: ...

def _(xs: Item | Sequence[Item]):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: Sequence[Item]
        for x in xs:
            reveal_type(x)  # revealed: Item
    else:
        reveal_type(xs)  # revealed: Item

Narrowing from (non-final) OpenItem | Sequence[OpenItem] via isinstance(.., Sequence):

class OpenItem: ...

def _(xs: OpenItem | Sequence[OpenItem]):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: (OpenItem & Sequence[object]) | Sequence[OpenItem]
        for x in xs:
            reveal_type(x)  # revealed: object
    else:
        reveal_type(xs)  # revealed: OpenItem & ~Sequence[object]

Invariance

Narrowing from object via isinstance(.., list):

def _(xs: object):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: Top[list[Unknown]]
        for x in xs:
            reveal_type(x)  # revealed: object

        # This is an error in strict mode:
        # error: [invalid-argument-type] "Expected `Never`, found `Literal[1]`"
        xs.append(1)

    else:
        reveal_type(xs)  # revealed: ~Top[list[Unknown]]

Narrowing from Item | list[Item] via isinstance(.., list):

from typing import final

@final
class Item: ...

def _(xs: Item | list[Item]):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: list[Item]
        for x in xs:
            reveal_type(x)  # revealed: Item
    else:
        reveal_type(xs)  # revealed: Item

Narrowing from (non-final) OpenItem | list[OpenItem] via isinstance(.., list):

class OpenItem: ...

def _(xs: OpenItem | list[OpenItem]):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: (OpenItem & Top[list[Unknown]]) | list[OpenItem]
        for x in xs:
            reveal_type(x)  # revealed: object
    else:
        reveal_type(xs)  # revealed: OpenItem & ~Top[list[Unknown]]

Exhaustiveness checking

def _(xs: list[str] | set[str]) -> str:
    if isinstance(xs, list):
        return "it's a list!"
    elif isinstance(xs, set):
        return "it's a set!"

Invariance with bounded type variables

A value of a type variable bounded by str can also be an instance of a Box specialization through multiple inheritance. Checking isinstance(value, Box) cannot establish that this specialization is Box[T], so the intersection with T survives and the return is rejected.

class Box[T]:
    value: T

def narrow_box[T: str](value: Box[T] | T) -> Box[T]:
    if isinstance(value, Box):
        reveal_type(value)  # revealed: Box[T@narrow_box] | (T@narrow_box & Top[Box[Unknown]])
        return value  # error: [invalid-explicit-return]

    reveal_type(value)  # revealed: T@narrow_box & ~Top[Box[Unknown]]
    raise TypeError

Gradual mode

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = false

Covariance

Narrowing from object via isinstance(.., Sequence):

from typing import Sequence, final

def _(xs: object):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: Sequence[Unknown]
        for x in xs:
            reveal_type(x)  # revealed: Unknown
    else:
        reveal_type(xs)  # revealed: ~Sequence[object]

Narrowing from Item | Sequence[Item] via isinstance(.., Sequence):

@final
class Item: ...

def _(xs: Item | Sequence[Item]):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: Sequence[Item]
        for x in xs:
            reveal_type(x)  # revealed: Item
    else:
        reveal_type(xs)  # revealed: Item

Narrowing from (non-final) OpenItem | Sequence[OpenItem] via isinstance(.., Sequence):

class OpenItem: ...

def _(xs: OpenItem | Sequence[OpenItem]):
    if isinstance(xs, Sequence):
        reveal_type(xs)  # revealed: (OpenItem & Sequence[Unknown]) | Sequence[OpenItem]
        for x in xs:
            reveal_type(x)  # revealed: Unknown | OpenItem
    else:
        reveal_type(xs)  # revealed: OpenItem & ~Sequence[object]

Invariance

Narrowing from object via isinstance(.., list):

def _(xs: object):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: list[Unknown]
        for x in xs:
            reveal_type(x)  # revealed: Unknown

        xs.append(1)
        xs.append("foo")

    else:
        reveal_type(xs)  # revealed: ~Top[list[Unknown]]

Narrowing from Item | list[Item] via isinstance(.., list):

from typing import final

@final
class Item: ...

def _(xs: Item | list[Item]):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: list[Item]
        for x in xs:
            reveal_type(x)  # revealed: Item
    else:
        reveal_type(xs)  # revealed: Item

Narrowing from (non-final) OpenItem | list[OpenItem] via isinstance(.., list):

class OpenItem: ...

def _(xs: OpenItem | list[OpenItem]):
    if isinstance(xs, list):
        reveal_type(xs)  # revealed: (OpenItem & list[Unknown]) | list[OpenItem]
        for x in xs:
            reveal_type(x)  # revealed: Unknown | OpenItem
    else:
        reveal_type(xs)  # revealed: OpenItem & ~Top[list[Unknown]]

Exhaustiveness checking

def _(xs: list[str] | set[str]) -> str:
    if isinstance(xs, list):
        return "it's a list!"
    elif isinstance(xs, set):
        return "it's a set!"

Invariance with bounded type variables

A value of a type variable bounded by str can also be an instance of a Box specialization through multiple inheritance. In gradual mode, isinstance(value, Box) preserves this overlap using Box[Unknown], which is assignable to Box[T], so the return statement is (unsoundly) accepted.

class Box[T]:
    value: T

def narrow_box[T: str](value: Box[T] | T) -> Box[T]:
    if isinstance(value, Box):
        reveal_type(value)  # revealed: Box[T@narrow_box] | (T@narrow_box & Box[Unknown])
        return value

    reveal_type(value)  # revealed: T@narrow_box & ~Top[Box[Unknown]]
    raise TypeError

Narrowing recursively bounded generics (strict mode)

An isinstance() check must not recurse indefinitely when a generic bound refers to its own class.

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = true
from typing import Any

class Recursive[T: "Recursive[Any]"]: ...

def narrow(value: object) -> None:
    if isinstance(value, Recursive):
        reveal_type(value)  # revealed: Recursive[object]

A self-referential bound must also be safe when its recursion is hidden behind a type alias.

class AliasedRecursive[T: "RecursiveAlias"]: ...

type RecursiveAlias = AliasedRecursive[Any]

def narrow_alias(value: object) -> None:
    if isinstance(value, AliasedRecursive):
        reveal_type(value)  # revealed: AliasedRecursive[object]

The same cycle recovery must handle bounds shared by mutually recursive generic classes.

class Left[T: "Right[Any]"]: ...
class Right[U: Left[Any]]: ...

def narrow_mutual(value: object) -> None:
    if isinstance(value, Left):
        reveal_type(value)  # revealed: Left[object]

    if isinstance(value, Right):
        reveal_type(value)  # revealed: Right[object]

Narrowing recursively bounded generics (gradual mode)

An isinstance() check must not recurse indefinitely when a generic bound refers to its own class.

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = false
from typing import Any

class Recursive[T: "Recursive[Any]"]: ...

def narrow(value: object) -> None:
    if isinstance(value, Recursive):
        reveal_type(value)  # revealed: Recursive[Unknown]

A self-referential bound must also be safe when its recursion is hidden behind a type alias.

class AliasedRecursive[T: "RecursiveAlias"]: ...

type RecursiveAlias = AliasedRecursive[Any]

def narrow_alias(value: object) -> None:
    if isinstance(value, AliasedRecursive):
        reveal_type(value)  # revealed: AliasedRecursive[Unknown]

The same cycle recovery must handle bounds shared by mutually recursive generic classes.

class Left[T: "Right[Any]"]: ...
class Right[U: Left[Any]]: ...

def narrow_mutual(value: object) -> None:
    if isinstance(value, Left):
        reveal_type(value)  # revealed: Left[Unknown]

    if isinstance(value, Right):
        reveal_type(value)  # revealed: Right[Unknown]

Narrowing generic defaults in Python 3.13

When a type parameter has a bare Any default, narrowing still materializes the substituted typevar. The default isn't used during isinstance narrowing (the type parameter gets Unknown instead), so the default value is irrelevant here:

[environment]
python-version = "3.13"

[analysis]
strict-generic-narrowing = true
from typing import Any

class WithAnyDefault[T = Any]:
    y: tuple[Any, T]

def _(x: object):
    if isinstance(x, WithAnyDefault):
        reveal_type(x.y)  # revealed: tuple[Any, object]

Type alias defaults substituted into type parameters still need to be materialized when narrowing:

from typing import Any

type A = Any

class WithAliasDefault[T = A]:
    y: tuple[A, T]

def _(x: object):
    if isinstance(x, WithAliasDefault):
        reveal_type(x.y)  # revealed: tuple[A, object]

isinstance(value, Box) checks the runtime class, not the type argument used to specialize it. Narrowing must therefore preserve the original type argument instead of substituting Box's default.

from typing import assert_never, final

@final
class Box[T: str = str]:
    value: T

    def __init__(self, value: T) -> None: ...

def box_with_default[T: str = str](value: Box[T] | T) -> Box[T]:
    if isinstance(value, Box):
        reveal_type(value)  # revealed: Box[T@box_with_default]
        return value

    if not isinstance(value, Box):
        reveal_type(value)  # revealed: T@box_with_default
        return Box[T](value)

    assert_never(value)

When isinstance() narrows a value of type object to a tuple subclass, its type argument comes from the declared upper bound, not the default. Its element types are inherited from the specialized base.

class DefaultedTuple[T: int = bool](tuple[T, str]): ...

def narrow_defaulted_tuple(value: object) -> None:
    if isinstance(value, DefaultedTuple):
        reveal_type(value)  # revealed: DefaultedTuple[int]
        reveal_type(value[0])  # revealed: int
        reveal_type(value[1])  # revealed: str

Negative narrowing also excludes gradual specializations of the defaulted tuple subclass.

def excludes_defaulted_tuple(value: DefaultedTuple[Any] | bool) -> bool:
    if isinstance(value, DefaultedTuple):
        reveal_type(value)  # revealed: DefaultedTuple[int & Any]
        reveal_type(value[0])  # revealed: int & Any
        reveal_type(value[1])  # revealed: str
        return False

    reveal_type(value)  # revealed: bool
    return value

Narrowing bounded generic defaults in gradual mode

In gradual mode, narrowing a value of type object to a tuple subclass leaves its type argument Unknown.

[environment]
python-version = "3.13"

[analysis]
strict-generic-narrowing = false
class DefaultedTuple[T: int = bool](tuple[T, str]): ...

def narrow_defaulted_tuple(value: object) -> None:
    if isinstance(value, DefaultedTuple):
        reveal_type(value)  # revealed: DefaultedTuple[Unknown]
        reveal_type(value[0])  # revealed: Unknown
        reveal_type(value[1])  # revealed: str

Narrowing generic classmethod

After an isinstance(..., classmethod) branch unwraps and replaces a generic classmethod, the false-branch residual should be impossible. This avoids retaining a classmethod[...] & Top[...] arm that later causes call-to-function-with-unknown-signature false positives.

[environment]
python-version = "3.13"
from collections.abc import Callable
from typing import Any, ParamSpec, TypeVar, cast

P = ParamSpec("P")
R = TypeVar("R")

def f(fn: Callable[P, R] | classmethod[Any, P, R]) -> Callable[P, R]:
    if isinstance(fn, classmethod):
        fn = cast(Callable[P, R], fn.__func__)

    if not callable(fn):
        raise TypeError

    reveal_type(fn)  # revealed: (**P@f) -> R@f
    return fn

Narrowing with TypedDict unions

Narrowing unions of int and multiple TypedDicts using isinstance(x, dict) should not panic during type ordering of normalized intersection types. Regression test for https://github.com/astral-sh/ty/issues/2451.

from typing import Any, TypedDict, cast

class A(TypedDict):
    x: str

class B(TypedDict):
    y: str

T = int | A | B

def test(a: Any, items: list[T]) -> None:
    combined = a or items
    v = combined[0]
    if isinstance(v, dict):
        cast(T, v)  # no panic

Narrowing with named expressions (walrus operator)

When isinstance() is used with a named expression, the target of the named expression should be narrowed. When the isinstance() check is the value of a named expression, its argument should also be narrowed.

def get_value() -> int | str:
    return 1

def f():
    if isinstance(x := get_value(), int):
        reveal_type(x)  # revealed: int
    else:
        reveal_type(x)  # revealed: str

    value = get_value()
    if result := isinstance(value, int):
        reveal_type(value)  # revealed: int
        reveal_type(result)  # revealed: Literal[True]
    else:
        reveal_type(value)  # revealed: str
        reveal_type(result)  # revealed: Literal[False]

Preserving TypedDict interfaces when narrowing mappings

A TypedDict is always a dictionary at runtime, but its static interface deliberately disallows operations that could remove required keys or introduce undeclared ones. Narrowing to dict, Mapping, or MutableMapping must not discard these restrictions.

Use a TypedDict with one required key and one optional key to distinguish safe operations from those that could invalidate its declared shape.

from typing import TypedDict, Mapping, MutableMapping
from typing_extensions import NotRequired

class Payload(TypedDict):
    key: int
    optional: NotRequired[str]

Narrowing directly to dict preserves both the required-key restrictions and the optional key's known type.

def narrow_typed_dict_to_dict(value: int | Payload) -> None:
    if isinstance(value, dict):
        reveal_type(value)  # revealed: Payload
        reveal_type(value["key"])  # revealed: int
        value["key"] = 1
        value["optional"] = "present"
        reveal_type(value.pop("optional"))  # revealed: str

        # error: [missing-attribute]
        value.clear()
        # error: [invalid-argument-type] "Cannot pop required field 'key' from TypedDict `Payload`"
        value.pop("key")
        # error: [invalid-typed-dict-key] "Unknown key "unexpected" for TypedDict `Payload`"
        value["unexpected"] = 1
        # error: [invalid-argument-type] "Cannot delete required key "key" from TypedDict `Payload`"
        del value["key"]

Same for MutableMapping:

def narrow_typed_dict_to_mutable_mapping(value: Payload) -> None:
    if isinstance(value, MutableMapping):
        reveal_type(value)  # revealed: Payload
        # error: [missing-attribute]
        value.clear()

And for Mapping:

def narrow_typed_dict_to_mapping(value: Payload) -> None:
    if isinstance(value, Mapping):
        reveal_type(value)  # revealed: Payload
        # error: [missing-attribute]
        value.clear()

A type alias must retain the same TypedDict interface.

PayloadAlias = Payload

def narrow_aliased_typed_dict_to_dict(value: PayloadAlias) -> None:
    if isinstance(value, dict):
        reveal_type(value)  # revealed: Payload
        # error: [missing-attribute]
        value.clear()

Iterable element types with permissive generic narrowing

After narrowing Iterable[T] | T to a non-sized iterable, T might itself be an iterable whose items have a different type. Permissive narrowing represents that possibility with Unknown, so the constructor infers list[T | Unknown]. Its acceptance as Collection[T] | T is unsound; it does not establish that all elements have type T.

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = false
from collections.abc import Collection, Iterable, Sized

def maybe_iterable_to_list[T](value: Iterable[T] | T) -> Collection[T] | T:
    if isinstance(value, Iterable) and not isinstance(value, Sized):
        # revealed: list[T@maybe_iterable_to_list | Unknown]
        reveal_type(list(value))
        # revealed: list[T@maybe_iterable_to_list]
        return reveal_type(list(value))
    raise NotImplementedError

Iterable element types with strict generic narrowing

Strict narrowing represents the unknown iterable element type with object. The constructor therefore infers list[object], and returning it as Collection[T] | T is correctly rejected.

[environment]
python-version = "3.12"

[analysis]
strict-generic-narrowing = true
from collections.abc import Collection, Iterable, Sized

def maybe_iterable_to_list[T](value: Iterable[T] | T) -> Collection[T] | T:
    if isinstance(value, Iterable) and not isinstance(value, Sized):
        # revealed: list[object]
        reveal_type(list(value))
        # error: [invalid-explicit-return]
        # revealed: list[object]
        return reveal_type(list(value))
    raise NotImplementedError