python / python/typing

Need type hint for `getattr`

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

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

topic: feature
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ả

from __future__ import annotations

from typing import Callable, Generator, LiteralString, Self, Tuple


class Callbacks[**P, T]:
    def __init__(self, funcs: Generator[Callable[P, T]]):
        self.funcs = funcs

    def __call__(self, *args: P.args, **kwargs: P.kwargs):
        return [func(*args, **kwargs) for func in self.funcs]


class CallBatch[T]:
    def __init__(self, objs: Generator[T]):
        self.objs = objs

    def __getattr__[ITEM:LiteralString](self, item:ITEM):
        return Callbacks(getattr(obj, item) for obj in self.objs)


class A:
    instances_pool = dict[str, Self]()

    @classmethod
    def get(cls, x: str, y: int):
        id = cls.get_id(x, y)
        if id in cls.instances_pool:
            return cls.instances_pool[id]
        return cls(x, y)

    @classmethod
    def get_id(cls, x: str, y: int):
        return f"{x}_{y}"

    @classmethod
    def call_batch(cls, *xy: Tuple[str, int]):
        return CallBatch[Self](cls.get(x, y) for x, y in xy)

    def __init__(self, x: str, y: int):
        self.x = x
        self.y = y
        self.id = self.get_id(x, y)
        self.instances_pool[self.id] = self

    def get_x(self):
        return self.x

    def get_y(self):
        return self.y


x = A.call_batch(("1", 1), ("2", 2)).get_x()
x = A.call_batch(("1", 1), ("2", 2)).get_y()

Image
I want type inference for Callbacks.
To achieve this, abilities blow should be support:

  1. CallBatch/__getattr__/item can be marked as type of attributes types of T(may be a LiteralString)
  2. getattr should have two generic types, one is type of object, the other is type of input name, and change return type when input name changes

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

  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.

Hướng nghiên cứu

Bắt đầu với ví dụ CallBatch và Callbacks được cung cấp, tập trung vào CallBatch.getattr và hành vi getattr generic được yêu cầu. Công việc được xem là hoàn thành khi các lệnh gọi get_x và get_y thể hiện các kiểu callback được suy luận thay đổi theo tên của thuộc tính được truy cập, như mô tả trong issue.

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
25/100

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.