Skip to content

Add a strictness flag that disables the bivariant behavior of TypeGuard #11230

@KotlinIsland

Description

@KotlinIsland
from typing import TypeGuard


def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)

l1: list[object] = []
l2 = l1

if is_str_list(l1):
    l2.append(1)
    impostor: str = l1[0]  # SUS ALERT!!!! 😳😳😳😳😳😳😳

I can't stand bivariance, and I believe it should always be an opt-in behavior. I don't know any other place in python typing where bivariance exists (except for an Any generic parameter).

Please add a strictness flag that enforces standard python typing variance rules on TypeGuard.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions