Search code examples
pythonpython-3.xmypy

How to avoid mypy complaints when inheriting from a built-in collection type?


Running mypy on code like this

class MySpecialList(list):
   # funky extra functionality

gives me

my_file.py:42: error: Missing type parameters for generic type "list"  [type-arg]

I can avoid this by not inheriting from list at all or ignoring this error.

But how should I deal with this? Isn't this a bug in mypy?


Solution

  • This is the result of using --disallow-any-generics (which is implied by --strict), as list is equivalent to list[Any]. You can fix it by making MySpecialist explicitly generic via a type variable.

    from typing import TypeVar
    
    
    T = TypeVar('T')
    
    
    class MySpecialList(list[T]):
        ...