Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mypy tries to instantiate an abstract class #12624

Closed
tal-zvon opened this issue Apr 19, 2022 · 1 comment
Closed

Mypy tries to instantiate an abstract class #12624

tal-zvon opened this issue Apr 19, 2022 · 1 comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions

Comments

@tal-zvon
Copy link

mypy version 0.942

With test.py like this:

from abc import ABC, abstractmethod

class AbstractClass(ABC):
    @abstractmethod
    def method(self):
        pass

class ConcreteClass1(AbstractClass):
    def method(self):
        print("hello")

class ConcreteClass2(AbstractClass):
    def method(self):
        print("hello")

class ConcreteClass3(AbstractClass):
    def method(self):
        print("hello")

classes = [
    ConcreteClass1,
    ConcreteClass2,
    ConcreteClass3,
]

for c in classes:
    c().method()

Mypy shows:

test.py:27: error: Cannot instantiate abstract class "AbstractClass" with abstract attribute "method"

Some weird behavior I've noticed:

If, instead of a loop, I do this:

...
ConcreteClass1().method()
ConcreteClass2().method()
ConcreteClass3().method()

mypy is happy.

Also, if, instead of 3 classes in the loop, I do 2:

classes = [
    ConcreteClass1,
    ConcreteClass2,
    #ConcreteClass3,
]

for c in classes:
    c().method()

mypy is happy with that as well.
I posted this on stackoverflow, and this seems to be a bug.

This can be worked around by explicitly defining the type of list:

classes: List[Type[AbstractClass]] = [
    ConcreteClass1,
    ConcreteClass2,
    ConcreteClass3,
]
@tal-zvon tal-zvon added the bug mypy got something wrong label Apr 19, 2022
@AlexWaygood AlexWaygood added the topic-join-v-union Using join vs. using unions label Apr 19, 2022
@AlexWaygood
Copy link
Member

Duplicate of #3115

@AlexWaygood AlexWaygood marked this as a duplicate of #3115 Apr 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions
Projects
None yet
Development

No branches or pull requests

2 participants