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

Doesn't quite understand that dynamically created classes are classes #50

Open
wiml opened this issue Apr 16, 2021 · 1 comment
Open

Comments

@wiml
Copy link

wiml commented Apr 16, 2021

Python allows you to create new classes using the three-argument form of the type() builtin. I can't tell if it's a mypy-zope problem or a mypy problem, but this doesn't typecheck properly:

import zope.interface
from zope.interface import Interface, Attribute, declarations

class IFoo(Interface):
    x = Attribute("Some thing or other")

class NormalClass:
    x = 12
declarations.classImplements(NormalClass, IFoo)

print(list(zope.interface.implementedBy(NormalClass)))

DynamicClass = type("DynamicClass", (object,), { "x": 42 })
declarations.classImplements(DynamicClass, IFoo)

print(list(zope.interface.implementedBy(DynamicClass)))

In this example NormalClass and DynamicClass are equivalent (except for their names and the initial value of x). At runtime they behave similarly and the classImplements() calls do what you'd think. Mypy however produces this error:

error: dyntest.DynamicClass is not a class, cannot mark it as a interface implementation  [misc]
@fschulze
Copy link

I get a similar issue when I try to pass in the class of an instance with .__class__. I use that in an adapter to mark classes I don't control as having an interface and verifying it afterwards. I already tried these variants on a wrapper function:


T = TypeVar("T")

def get_class(obj: T) -> Type[T]:
    return obj.__class__
def get_class(obj: Any) -> Type[Any]:
    return obj.__class__

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

No branches or pull requests

2 participants