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

make it possible to define a generic interface #95

Open
glyph opened this issue Mar 13, 2023 · 0 comments
Open

make it possible to define a generic interface #95

glyph opened this issue Mar 13, 2023 · 0 comments

Comments

@glyph
Copy link

glyph commented Mar 13, 2023

This probably requires some implementation support from the zope.interface side, but I find myself wanting to be able to write this:

from dataclasses import dataclass
from typing import Generic, TypeVar

from zope.interface import Interface, implementer

T = TypeVar("T")

class IA(Generic[T], Interface):
    def m() -> T:
        ...

@implementer(IA)
@dataclass
class A(Generic[T]):
    _v: T
    def m(self) -> T:
        return self._v

a: IA[int] = A(3)

This actually appears to do what I want at type-check time! But then it (somewhat obviously) crashes at runtime.

This horrible hack almost works though, which suggests that this could work properly with some very small changes:

# from __future__ import annotations
from dataclasses import dataclass
from typing import Generic, TypeVar, TYPE_CHECKING

from zope.interface import Interface, implementer

T = TypeVar("T")

if TYPE_CHECKING:
    from typing import Generic as GenericInterface
else:
    from zope.interface.interface import InterfaceClass
    class SpecialInterfaceClass(InterfaceClass):
        def __getitem__(self, key):
            return self
    EmptyInterface = SpecialInterfaceClass("<Empty>", __module__=__name__)
    class GenericInterfaceClass:
        def __getitem__(self, typevars):
            return EmptyInterface
    GenericInterface = GenericInterfaceClass()

class IA(Interface, GenericInterface[T]):
    def m() -> T:
        ...

@implementer(IA)
@dataclass
class A(Generic[T]):
    _v: T
    def m(self) -> T:
        return self._v

@dataclass
class B:
    ...

a: IA[int] = A(3)               # works, hooray
a = B()                         # error, hooray
a = A("oops")                   # no error, boo
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

1 participant