Skip to content

Mixins with generic self and type bounds #7191

Closed
@zero323

Description

@zero323

Let's say I have a class

class Foo: ...

and a typevar with bound

from typing import TypeVar

T = TypeVar("T", bound=Foo)

Now I'd like to define a class that will be used as a mixin:

class MixIn:
    def foo(self: T) -> T: ...

I want to express two things here:

  • MixIn should be used only as a mixin with Foo (the idea is similar to Scala self-type. In other words this should type check:

    class Bar(Foo, MixIn): ...

    while this shouldn't:

    class Baz(MixIn): ...
  • MixIn.foo returns the same type as self (at least Foo with MixIn).

Additionally it should address issues like #5868 or #5837 with zero boilerplate.

Right now (0.720+dev.e479b6d55f927ed7b71d94e8632dc3921b983362) this fails:

from typing import TypeVar

class Foo: ...

T = TypeVar("T", bound=Foo)

class MixIn:
    def foo(self: T) -> T: ...
mypy --python-version 3.7 --strict-optional --no-site-packages --show-traceback --no-implicit-optional mixinwithgenericselfandbounds.py
mixinwithgenericselfandbounds.py:8: error: The erased type of self "mixinwithgenericselfandbounds.Foo" is not a supertype of its class "mixinwithgenericselfandbounds.MixIn"

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions