mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Sub-classing class returned from function fails

Open Raab70 opened this issue 6 years ago • 1 comments

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request? Bug

  • Please insert below the code you are checking with mypy, or a mock-up repro if the source is private. We would appreciate if you try to simplify your case to a minimal repro.

def get_cls():
    class A:
        pass

MyClass = get_cls()

class SubClass(MyClass):
    pass
  • What is the actual behavior/output?
❯ mypy test_typing.py
test_typing.py:7: error: Variable "test_typing.MyClass" is not valid as a type
test_typing.py:7: error: Invalid base class "MyClass"
Found 2 errors in 1 file (checked 1 source file)
  • What is the behavior/output you expect? Correct inference that the return is a class and not a class instance, or at least a way to add an annotation as such. I've tried a few different methods and nothing works.

  • What are the versions of mypy and Python you are using?

❯ python --version
Python 3.7.3
❯ mypy --version
mypy 0.761
  • Do you see the same issue after installing mypy from Git master? Yes:
test_typing.py:8: error: Variable "test_typing.MyClass" is not valid as a type
test_typing.py:8: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
test_typing.py:8: error: Invalid base class "MyClass"
Found 2 errors in 1 file (checked 1 source file)

Raab70 avatar Jul 27 '20 17:07 Raab70

You can explicitly annotate MyClass as Any, and mypy will allow it to be used as a base class:

MyClass: Any = get_cls()

class SubClass(MyClass):
    pass

The explicit annotation is required due to technical reasons, but also because using a variable as a base class turns off or weakens various checks implicitly, so we want an explicit hint that this is fine for the user.

JukkaL avatar Jul 31 '20 15:07 JukkaL