Types for "truthy" and "falsy" values
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 1.8k
- Fork
- 302
- Merge trung bình
- 23 giờ
- Pull request đã merge (30 ngày)
- 8
Mô tả
I found this function in our codebase and I'm trying to type it:
def run_until_truthy(fn, num_tries=5):
for _ in range(num_tries):
if res := fn():
return res
Exception('Giving up.')
The function repeatedly calls a callable without arguments until it returns a "truthy" value. Then it returns that value. Easy enough:
def run_until_truthy[T](fn: Callable[[], T], num_tries: int = 5) -> T: ...
This is correct but too restrictive. Usages like this don't work:
def load_something() -> str | None:
pass
# mypy: Incompatible types in assignment (expression has type "str | None", variable has type "str")
something: str = run_until_truthy(load_something)
I can hack it to make it work:
type Falsy = Literal[None, False, 0, "", b""] | tuple[()]
def run_until_truthy[T](fn: Callable[[], T | Falsy], num_tries: int = 5) -> T: ...
Does it make sense to add official Truthy and Falsy types to the standard library?
Maybe a Truthy type would also make sense. Truthy can't be defined as a type alias of existing types, but could probably also be useful sometimes, e.g. to type the following function:
def get_falsy_values[T](seq: list[T | Truthy]) -> list[T]:
return [i for i in seq if not i]
From thinking about it for a few minutes, I think Falsy would be more often useful than Truthy, at least in combination with the current typing features.
If there's an intersection type constructor at some point, the above examples could be written like this instead, which might be easier to understand:
def run_until_truthy[T](fn: Callable[[], T], num_tries: int = 5) -> T & Truthy: ...
def get_falsy_values[T](seq: list[T]) -> list[T & Falsy]:
2024-11-25
- Updated to PEP 695 syntax.
- Using
&instead ofIntersection[]in example using proposed intersection types.
Hướng dẫn đóng góp
Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này
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
Không có tệp triển khai hoặc bài kiểm thử nào được nêu tên. Hãy bắt đầu bằng việc xem xét các ví dụ truthy và falsy, sau đó đọc các đề xuất về intersection types được liên kết và hướng dẫn của typing project; công việc chỉ hoàn tất sau khi thiết kế và hành vi kiểm tra kiểu dự kiến được thống nhất, đồng thời hỗ trợ typing liên quan được đặc tả.
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
- tooling
- Loại issue
- Tính năng
- Độ 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
- Cần làm rõ
- Mức phù hợp với người mới
- 30/100