Constraints on generic class with multiple TypeVar's

Đang mở
#3,904 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
25/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
devtools

Hướng nghiên cứu

The issue provides a Python reproducer but names no source file or test. Start by running the example with mypy and locating the TypeVar, Generic, and overload-checking tests. Done means establishing whether paired constraints can be expressed and, if supported, adding coverage for the allowed and rejected combinations.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

feature priority-2-low

Is there a way to limit the possible combinations of TypeVar's instantiations for Generics with multiple TypeVar's?

Let's look at the following example:

import sys
from typing import TypeVar, Generic, overload

assert sys.version_info >= (3, 5)


class Foo(object):
    def __init__(self, dummy):
        self.dummy = dummy


class Bar(object):
    def __init__(self, dummy):
        self.dummy = dummy


class Apple(object):
    def __init__(self, dummy):
        self.dummy = dummy


class Pear(object):
    def __init__(self, dummy):
        self.dummy = dummy


Var1 = TypeVar('Var1', Foo, Apple)
Var2 = TypeVar('Var2', Bar, Pear)


@overload
def combine(left: Foo, right: Bar) -> None:
    ...


@overload
def combine(left: Apple, right: Pear) -> None:
    ...


def combine(left, right):
    print(left.dummy + " and " + right.dummy)


class MyClass(Generic[Var1, Var2]):
    def __init__(self, a: Var1) -> None:
        self.dummy = dummy  # type: Var1

    def add(self, other: Var2) -> None:
        combine(self.dummy, other)

Here, mypy produces this error output:

mypy_example.py:50: error: No overload variant of "combine" matches argument types [mypy_example.Foo*, mypy_example.Pear*]
mypy_example.py:50: error: No overload variant of "combine" matches argument types [mypy_example.Apple*, mypy_example.Bar*]

Is there any possibility to restrict MyClass to MyClass[Apple, Pear] and MyClass[Foo, Bar] but disallow MyClass[Apple, Bar] and MyClass[Foo, Pear]? This is for python 3.5.

Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Merge trung bình
1 ngày 18 giờ
Pull request đã merge (30 ngày)
54

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của python/mypy

Tất cả issue của python/mypy

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.