Skip to content

Specialized methods on generic classes #14243

Open
@Tinche

Description

@Tinche

Bug Report

Let's say I have a generic class G.

from __future__ import annotations

from collections.abc import Sized
from typing import Generic, TypeVar

T = TypeVar("T")

class G(Generic[T]):
    pass

I want to have a single method on this class that's only legal for a subset of T.

If I want to limit it to, say, int, it works:

class G(Generic[T]):
    def test(self: G[int]) -> G[int]:
        return self

G[int]().test()  # Works, as it should
G[str]().test()  # Error, as it should

But if I want to limit it to, say, a protocol like Sized, I get a false negative:

S = TypeVar("S", bound=Sized)

class G(Generic[T]):
    def test(self: G[S]) -> G[S]:
        return self


G[int]().test()  # False negative - works, but it shouldn't

This is a pity, since it'd unlock some cool features I was working on vis-a-vis using attrs attributes. Are there any workarounds? Would this be handled by intersection types maybe?

Your Environment

  • Mypy version used: mypy 1.0.0+dev.b8c03ab6809aab56928f3cd865edb44944a600a2
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.10.6

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions