Skip to content

Request: an AssertingTypeGuard type for TypeGuard-like semantics #930

Open
@sirosen

Description

@sirosen

There is a frequent pattern of TypeGuard-like functions which assert or otherwise raise an exception if a type constraint is not met.

For example, microsoft/pyright#2007 points to a case in which unittest provides assertIsNotNone, but a type-checker cannot infer that type narrowing has occurred. Arguably, the popular typeguard library is based around an implementation of "asserting" type guards. (One which deduces what assertions should be made from the annotations.)

TypeGuards allow for semantics like

y: str
assert is_list_of_str(x)
assert len(x) > 0
y = x[0]

An AssertingTypeGuard would allow for

y: str
assert_is_nonempty_list_of_str(x)  # note, this encodes another runtime check, the len check
y = x[0]

This becomes especially valuable if we consider that you might not want to do this all with assert. I may, as an author, prefer my own custom exceptions, e.g.

def assert_is_nonempty_list_of_str(x) -> AssertingTypeGuard[list[str]]:
    if not isinstance(x, list):
        raise ExpectedListError(x)
    if not x:
        raise EmptyContainerError(x)
    if not all(isinstance(y, str) for y in x):
        raise ContainedInvalidTypeError(x, str)
    return x

(Apologies if this repo is the wrong place to submit this request/idea. I'm happy to go through another process if necessary.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions