Skip to content

contextlib.ContextDecorator.__call__ incorrect type #4382

Closed
@ap--

Description

@ap--

Dear typeshed team,

I have run into the following typing issue when using contextlib.ContextDecorator and analysing via mypy:

# minimal example
from contextlib import ContextDecorator

class MyDecorator(ContextDecorator):
    def __enter__(self):
        pass
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

@MyDecorator()
def func() -> int:
    return 1

Returns the following Error:

/scratch.py:10: error: Argument 1 to "__call__" of "ContextDecorator" has incompatible type "Callable[[], int]"; expected "Callable[..., None]"
Found 1 error in 1 file (checked 1 source file)

I believe the current typeshed annotation is incorrect:

class ContextDecorator:
def __call__(self, func: Callable[..., None]) -> Callable[..., ContextManager[None]]: ...

I think it should be:

 class ContextDecorator: 
     def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]: ... 

That would make it consistent with the `functool.wraps` annotation:

def wraps(
wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...
) -> Callable[[_AnyCallable], _AnyCallable]: ...

which is used in the contextlib.ContextDecorator.__call__ implementation:
https://github.com/python/cpython/blob/cadda52d974937069eeebea1cca4229e2bd400df/Lib/contextlib.py#L75-L80

I'd be happy to submit a PR if my error analysis is correct.
Cheers,
Andreas 😃

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions