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

Dynamic base classes #2813

Closed
JukkaL opened this issue Feb 6, 2017 · 2 comments
Closed

Dynamic base classes #2813

JukkaL opened this issue Feb 6, 2017 · 2 comments
Labels

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Feb 6, 2017

Currently mypy isn't happy about dynamic base classes, even though these are not uncommon. Maybe mypy could do a better job.

Currently this works:

base: Any = create_class()

class A(base): ...

However, these don't work:

base2 = create_class()  # no annotation for base2 -> doesn't work
class B(base2): ...

class C(create_class()): ...  # function call as base class

base3: Type[A] = ...
class D(base3): ...

A plugin architecture (#1240) would help with commonly used libraries, but it wouldn't help with more ad-hoc uses of dynamic base classes.

@danmou
Copy link

danmou commented Mar 20, 2019

Another use-case for dynamic base classes is in class decorators. For example:

from typing import ContextManager, Type

def decorator(cls: Type[ContextManager]) -> Type[ContextManager]:
    class Decorated(cls):
        pass
    return Decorated

@decorator
class TestClass(ContextManager):
    pass

This fails with:

test.py:4: error: Invalid type "cls"
test.py:4: error: Invalid base class

Even using a more generic annotation such as Type or Any doesn't work. The only workaround I've found to get rid of the error is:

def decorator(cls: Type[ContextManager]) -> Type[ContextManager]:
    cls_: Any = cls
    class Decorated(cls_):
        pass
    return Decorated

@msullivan
Copy link
Collaborator

We've got a plugin system that supports this now and I doubt we'll do better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants