Skip to content
New issue

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

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

Already on GitHub? # to your account

contextmanager wrapping a method using ParamSpec fails to infer correct type #15002

Closed
AxelVoitier opened this issue Apr 3, 2023 · 3 comments
Labels
bug mypy got something wrong

Comments

@AxelVoitier
Copy link

AxelVoitier commented Apr 3, 2023

Bug Report

When using contextmanager decorator on an object method, which uses a ParamSpec, then the inferred type of the resulting method seems to be one for an unbounded method. And therefore it expects an extra "self" parameter at the beginning.

To Reproduce

from contextlib import contextmanager
from typing import Iterator, ParamSpec, Generic, reveal_type

_P = ParamSpec('_P')

class AClass(Generic[_P]):

    @contextmanager
    def a_cm_with_param_spec(self, *args: _P.args, **kwargs: _P.kwargs) -> Iterator[None]:
        yield

an_object = AClass[(int, str)]()

with reveal_type(an_object.a_cm_with_param_spec)(12, 'hello'):
    pass

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

Expected Behavior

Expecting no error.
Revel type should have shown something like def (builtins.int, builtins.str) -> contextlib._GeneratorContextManager[None]

Actual Behavior

main.py:16: error: Too few arguments for "a_cm_with_param_spec" of "AClass"  [call-arg]
main.py:16: note: Revealed type is "def (self: __main__.AClass[[builtins.int, builtins.str]], builtins.int, builtins.str) -> contextlib._GeneratorContextManager[None]"
main.py:16: error: Argument 1 to "a_cm_with_param_spec" of "AClass" has incompatible type "int"; expected "AClass[[int, str]]"  [arg-type]
main.py:16: error: Argument 2 to "a_cm_with_param_spec" of "AClass" has incompatible type "str"; expected "int"  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11

Comments

@AxelVoitier AxelVoitier added the bug mypy got something wrong label Apr 3, 2023
@AxelVoitier
Copy link
Author

Initial comment updated with mypy 1.2.0 behaviour (ie. the error on the contextmanager declaration disappeared).

@ilevkivskyi
Copy link
Member

This works on master.

@hauntsaninja
Copy link
Collaborator

@AxelVoitier is the project you were running into this on open source?

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants