Skip to content

Properly type hinting a decorator which creates async context managers #898

Answered by ronf
ronf asked this question in Q&A
Discussion options

You must be logged in to vote

I got a chance to look at this again today, and found the issue! It turns out that the definition of __aexit__ in both _Wrapper and _MyCtxMgr was slightly off, missing "Optional" on some of the arguments, and thus making those classes incompatible with the binding on R to match the protocol AsyncContextManager. Here's a corrected version:

import asyncio
import functools
from types import TracebackType
from typing import Any, AsyncContextManager, Awaitable, Callable, Generator
from typing import Generic, Optional, ParamSpec, Type, TypeVar

R = TypeVar('R', bound=AsyncContextManager)

class _Wrapper(Generic[R]):
    def __init__(self, coro: Awaitable[R]):
        self._coro = coro
        self

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
8 replies
@JelleZijlstra
Comment options

@ronf
Comment options

@ronf
Comment options

@JelleZijlstra
Comment options

@ronf
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by ronf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants