mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Mypy cannot determine the type of the declared field inside a protocol method

Open UniverseFly opened this issue 1 year ago • 4 comments

Bug Report

Mypy cannot determine the type of the declared field inside a protocol method.

To Reproduce

Invoke mypy on the following Python file

# bug.py
from typing import Protocol

class Test(Protocol):
    k: int

    def test(self, i: int):
        self.k = self.k

Mypy complains: bug.py:7: error: Cannot determine type of "k". Strange here is if I remove the parameter i, the error would disappear.

Expected Behavior

No such error.

My Environment

  • Mypy version used: https://github.com/python/mypy@e3827a1b950f83332656ad9c51ca8eea06ea2234
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.4
  • Operating system and version: Ubuntu 20.04.4

UniverseFly avatar Sep 21 '22 03:09 UniverseFly

Strange here is if I remove the parameter i, the error would disappear.

I think that's just because mypy doesn't check functions that are completely unannotated. You still get the weird error for the following snippet, which doesn't have the i parameter, but does have a return annotation:

from typing import Protocol

class Test(Protocol):
    k: int

    def test(self) -> None:
        self.k = self.k  # error: Cannot determine type of "k"

https://mypy-play.net/?mypy=0.971&python=3.10&gist=d7a6bc98b693ad31605c3df9c83906d4

AlexWaygood avatar Sep 22 '22 17:09 AlexWaygood

from typing import Protocol

class Test(Protocol):
    k: int

    def test(self) -> None:
        self.k = self.k  # error: Cannot determine type of "k"

In your case, the test method is annotated (-> None), isn't it? Then why is there still an error?

UniverseFly avatar Sep 22 '22 23:09 UniverseFly

Mypy (by default) only checks methods that do have annotations.

JelleZijlstra avatar Sep 23 '22 01:09 JelleZijlstra

Mypy (by default) only checks methods that do have annotations.

Thanks for your comment. But still, the program shown by @AlexWaygood through the link can not type check. The same error lies in the latest mypy.

  • https://mypy-play.net/?mypy=0.971&python=3.10&gist=d7a6bc98b693ad31605c3df9c83906d4

UniverseFly avatar Jan 14 '23 21:01 UniverseFly

This bug appears to have been fixed in mypy 1.4.0.

erictraut avatar Aug 13 '23 20:08 erictraut