Type[T] -> T has a strange behaviour
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 20.6k
- Fork
- 3.3k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
This bug report is coming from https://github.com/python/mypy/issues/8946 and https://github.com/ltworf/typedload/issues/132
Basically the pattern
def f(t: Type[T]) -> T: ...
Works for some types but not others, and I can't see a pattern. For example it will work for a NamedTuple but not for a Tuple.
See this example:
from typing import *
from dataclasses import dataclass
T = TypeVar('T')
@dataclass
class P:
a: int
class Q(NamedTuple):
a: int
def create(t: Type[T]) -> T: ...
# These ones work
reveal_type(create(int))
reveal_type(create(str))
reveal_type(create(List[int]))
reveal_type(create(Dict[int, int]))
reveal_type(create(Q))
reveal_type(create(P))
# These do not
reveal_type(create(Tuple[int]))
reveal_type(create(Union[int,str]))
reveal_type(create(Optional[int]))
Now in the older mypy, the ones that do not work would just be understood as Any, which is absolutely not the intended behaviour. In the latest release instead they fail with error: Argument 1 to "create" has incompatible type "object"; expected "Type[<nothing>]" (and I have no idea of what this means).
Anyway in my view, all of the examples provided should work.
In case I'm wrong, then none of them should work, and probably a way to achieve this is needed.
Background: I am working on a library to load json-like things into more typed classes, and it promises to either return an object of the wanted type, or fail with an exception.
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- 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.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với trình tái hiện Python được cung cấp và chạy mypy với từng lệnh gọi reveal_type, so sánh các trường hợp hoạt động được với Tuple[int], Union[int, str] và Optional[int]. Theo dõi cách Type[T] và TypeVar[T] được suy luận cho các lệnh gọi đó; hoàn tất khi các ví dụ có các kiểu được suy luận nhất quán, đúng như dự kiến, hoặc hành vi được hỗ trợ được ghi lại rõ ràng và được bao phủ bởi các bài kiểm thử hồi quy.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- compilers
- Loại issue
- Lỗi
- Độ khó
- 5/5
- Thời gian dự kiến
- Hơn một tuần
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Khá rõ ràng
- Mức phù hợp với người mới
- 30/100