Type[...] doesn't work correctly with unions

Đang mở
#4,625 4 bình luận 4 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

No files or tests are named. Start by reproducing the two reveal_type examples for str and Optional[str], then investigate how mypy handles generic Type[T] calls with Union types. Done means the reported structure call infers the union or optional type instead of Any without requiring typing.cast.

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

Mô tả

bug priority-1-normal topic-union-types

I have a function called structure(json_obj, type) it takes a json like object and does some stuff to it and, if it can, returns an instance of type, otherwise it raises an error.

But it also supports Union and Optional which means a type annotation like
def structure(obj: Any, type: Type[T]) -> T:... doesn't work. (It returns Any for Unions) I see that typing.cast works correctly but I don't really want to have to write x = cast(Optional[str], structure(foo, Optional[str])) all over my code.

Here's some example code:

from typing import Optional, Type, Any, TypeVar
T = TypeVar('T')
def structure(obj: Any, type: Type[T]) -> T:...

reveal_type(structure('foo', str))  #  Revealed type is 'builtins.str*'
reveal_type(structure('foo', Optional[str]))  # Revealed type is 'Any'

I don't know how this signaling would be done though, without adding something to typing or telling mypy about your method through some other channel, e.g. config file (eww)

@typing.castlike
def structure(obj: Any, type: Type[T]) -> T:...
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.