Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Awaitable typeguards #1872

Open
alexdrydew opened this issue Oct 24, 2024 · 1 comment
Open

Awaitable typeguards #1872

alexdrydew opened this issue Oct 24, 2024 · 1 comment
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@alexdrydew
Copy link

Currently it seems impossible to have async TypeGuard or TypeIs:

from typing_extensions import TypeIs

async def foo(a: int | str) -> TypeIs[int]:
    raise NotImplementedError

async def main() -> None:
    a: int | str = 10
    if await foo(a):
        reveal_type(a)
    else:
        reveal_type(a)

Current specification is not clear about how async functions returning TypeIs or TypeGuards should be treated, but I believe this would be useful for async lazy evaluation of typestate fields, example:

from typing_extensions import TypeIs, TypeVar, Generic


T = TypeVar('T', int | None, int, None, covariant=True)


class A(Generic[T]):
    _a: T
    
    async def get_a(self: A[int | None]) -> int | None:
        a = 123  # imagine some expensive async operation, e.g. fetch value from API
        self._a = a
        return self._a
        
    def method_requires_a(self: A[int]) -> None:
        raise NotImplementedError
        
    def __init__(self):
        self._a = None

async def has_a(a: A[int | None]) -> TypeIs[A[int]]:
    return await a.get_a() is not None
 
 
async def main(a: A[int | None]):
    if await has_a(a):
        a.method_requires_a()  # currently fails as type was not narrowed
@alexdrydew alexdrydew added the topic: feature Discussions about new features for Python's type annotations label Oct 24, 2024
@RSzipper
Copy link

hello sir I am trying a compatible function which could solve this issue could you please describe me more about the issue or where do you need changes exactly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants