Search code examples
pythonmypypython-typingpyright

Nested Protocols are not checked by Mypy/Pylance


I'm using Protocols to define some base classes
I want to just inherit the parent Protocol and have the children type checked automatedly.

Here is the example code:

class Child(Protocol):
   name: str


class Parent(Protocol):
   Child: Child


class FooBar(Parent):
   class Child:
       pass
       # No Error

Why is Mypy/Pylance not inferring that the Child Protocol requires a name


Solution

  • This is a known limitation in mypy, here's the corresponding issue. As pointed out in comments, Pyright detects this type violation correctly. If you define the type externally and assign, mypy also identifies the error:

    from typing import Protocol
    
    
    class Child(Protocol):
       name: str
    
    class Parent(Protocol):
       Child: Child
    
    class _Child:
        pass
    
    class FooBar(Parent):
        Child = _Child  # E: Incompatible types in assignment (expression has type "type[_Child]", base class "Parent" defined the type as "Child")  [assignment]