Skip to content

Incorrect "incompatible type" error for context manager typed with AbstractContextManager #16260

Closed as not planned

Description

@gozdal

Bug Report

mypy considers a context manager created using contextlib.contextmanager to have incompatible type.

To Reproduce

import sys
from contextlib import contextmanager, AbstractContextManager


@contextmanager
def managed_resource() -> AbstractContextManager[str]:
    yield "foo"


def main():
    with managed_resource() as res:
        print(res)


if __name__ == '__main__':
    sys.exit(main())

Expected Behavior

mypy should accept this program without an error. mypy documentation refers to ContextManager which is a deprecated alias to AbstractContextManager

Actual Behavior

x.py:5: error: Argument 1 to "contextmanager" has incompatible type "Callable[[], AbstractContextManager[str]]"; expected "Callable[[], Iterator[<nothing>]]"  [arg-type]
x.py:6: error: The return type of a generator function should be "Generator" or one of its supertypes  [misc]

Your Environment

  • Mypy version used: mypy 1.6.0 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.11.5

Activity

  1. added
    bug
    on Oct 13, 2023
  2. AlexWaygood commented on Oct 13, 2023

    @AlexWaygood
    Member

    Your annotation is incorrect. Your return annotation for managed_resource needs to accurately reflect the return type of the managed_resource function as it exists before it is passed to the @contextmanager decorator. Changing your return annotation to Iterator or Generator will fix your error.

  3. gozdal commented on Oct 13, 2023

    @gozdal
    Author

    Why do you think it's incorrect?
    mypy docs refers to typing.ContextManager, which is an alias to AbstractContextManager.
    Typing it with Generator or Iterator does not work in PyCharm (i.e. PyCharm does not infer correct type). You could blame it on PyCharm, however I don't see why typing with AbstractContextManager is incorrect.
    I am not arguing it's correct but trying to understand your reasoning.

  4. AlexWaygood commented on Oct 13, 2023

    @AlexWaygood
    Member

    For a function with a decorator like this...

    @foo
    def bar(): ...

    ...At runtime, this is translated to this:

    def bar(): ...
    bar = foo(bar)

    Consider the annotations that the contextmanager function has in typeshed, which is vendored by mypy and used as the source of truth for the standard library. It says that contextmanager accepts any function that returns an Iterator, and returns a function that returns an instance of a class that conforms to the AbstractContextManager protocol that mypy describes in the docs that you're referencing:

    def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...

    When annotating functions that are decorated with decorators like @contextmanager that transform the type of the function like this, you need to use type annotations that describe the function before its type is transformed. Otherwise, mypy cannot validate that the function managed_resource is suitable to be passed to the contextmanager function.

    (i.e. PyCharm does not infer correct type)

    I'm afraid PyCharm is in the wrong here. https://youtrack.jetbrains.com/issue/PY-36444/PyCharm-doesnt-infer-types-when-using-contextlib.contextmanager-decorator looks relevant. You'll find that mypy, pyright and pyre all agree with me here. (I can't check with pytype, since I'm on Windows, and pytype doesn't support Windows.)

    https://pyright-playground.decorator-factory.su/?gzip=H4sIADQ4KWUC_22NPQ7CMAyFd5_CI5UKG0sHBGJi4ASIwUmdylISI9cD3B6kABKib_zeXzItGDVnji5a5w2FiFJuao4nZyNXg9RC1fnuWcLHf5NClSa2Hg9hdqPox8bPjQPsf4MwcsKkuupwvfueXKT6dQB86SGcR9wuFwNZKy6__c88AWPLwkLiAAAA

    https://pyre-check.org/play?input=%23%20pyre-strict%0Afrom%20collections.abc%20import%20Iterator%0Afrom%20contextlib%20import%20AbstractContextManager%2C%20contextmanager%0A%0A%40contextmanager%0Adef%20foo()%20->%20Iterator%5Bint%5D%3A%0A%20%20%20%20yield%204%0A%20%20%20%20%0A%40contextmanager%0Adef%20bar()%20->%20AbstractContextManager%5Bint%5D%3A%0A%20%20%20%20yield%205%0A%0A

    https://mypy-play.net/?mypy=latest&python=3.11&gist=18f17b0aee3337c6b4c401576da4dbf2

  5. gozdal commented on Oct 13, 2023

    @gozdal
    Author

    Thanks for in-depth explanation!

  6. socketpair commented on Sep 18, 2024

    @socketpair

    @AlexWaygood finally, what is the CORRECT typing ? (not that just works, but that IS correct) ?

  7. AlexWaygood commented on Sep 18, 2024

    @AlexWaygood
    Member

    @AlexWaygood finally, what is the CORRECT typing ? (not that just works, but that IS correct) ?

    from collections.abc import Generator
    
    @contextmanager
    def managed_resource() -> Generator[str, None, None]:
        yield "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions