Skip to content

Change PEP 647 to allow for narrowing in the negative case #926

@Zomatree

Description

@Zomatree

Currently PEP 647 doesnt narrow the type in the negative case, i feel like this should be changed to narrow in the negative case, currently due to it not narrowing its impossible to correctly type certain functions with typeguards fully, this came up in actual code a couple times, for example:

this example is used in conjuction with python/typeshed#5658

R_T = TypeVar("R_T")
P = ParamSpec("P")

async def maybe_coroutine(func: Callable[P, Union[R_T, Coroutine[Any, Any, R_T]]], *args: P.args, **kwargs: P.kwargs) -> R_T:
    value = func(*args, **kwargs)

    if isawaitable(value):
        value = await value

    return value

because value isnt narrowed to be R_T@maybe_coroutine outside the if statement its back to being a union even though it would never be awaitable because of the if statement, this feels like a massive downside and makes typeguard pretty useless for a lot of cases, forcing people to use cast or # type: ignore.

While this may cause a lot of controversy with changing a quite large part of how typeguards work, i feel like this is a needed change and a step in the right direction for making typing much more powerful and able to be properly integrated into more projects codebases without having to resort to ignoring or overwrites the type

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