Skip to content

Mypy does not recognize missing method #6990

Closed

Description

@cburgdorf

In the following example, mypy does not catch that self.meh() does not exist. Is this expected behavior because of the static False?

class TestCase:

    def foo(self) -> bool:
        return False and self.meh()

The original bug in our code base was harder to spot than this but it boils down to the same reason so I'm wondering if this is expected behavior.

If I change the example to

class TestCase:

    def foo(self) -> bool:
        return True and self.meh()

then mypy does in fact spot the missing meh method.

mypy_bug.py:5: error: "TestCase" has no attribute "meh"

Activity

  1. JelleZijlstra commented on Jun 13, 2019

    @JelleZijlstra
    Member

    Mypy doesn't type check code it thinks is unreachable. I'm personally not convinced that's the right behavior, because it can lead to hard-to-debug issues, but that's probably not something we can easily change.

  2. cburgdorf commented on Jun 14, 2019

    @cburgdorf
    Author

    Hey @JelleZijlstra thank you for your prompt reply!

    I'm personally not convinced that's the right behavior, because it can lead to hard-to-debug issues

    Yep, that's really unfortunate. In real code, these things can be far more subtle. The root cause in our case was a missing @property decorator as seen below.

    class TestCase():
     
        @property
        def is_running(self) -> bool:
            return not self.is_stopped and self.meh()
    
        #@property   # <-- if we forget the @property, the missing `meh` goes unnoticed
        def is_stopped(self) -> bool:
            return False

    If you add the property decorator, mypy will rightfully catch the missing meh() method but if you forget the property, the missing method just goes unnoticed.

  3. ilevkivskyi commented on Jun 15, 2019

    @ilevkivskyi
    Member

    One of the possible ways forward is to emit an error/warning when mypy skips some branch because it is unreachable, see #2395

  4. ilevkivskyi commented on Jun 17, 2019

    @ilevkivskyi
    Member

    Now that we have a dedicated issue #7008, I think we can close this as a duplicate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions