8000 Need type hint for `getattr` · Issue #2006 · python/typing · GitHub
[go: up one dir, main page]

Skip to content

Need type hint for getattr #2006

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
STofone opened this issue May 17, 2025 · 0 comments
Open

Need type hint for getattr #2006

STofone opened this issue May 17, 2025 · 0 comments
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@STofone
Copy link
STofone commented May 17, 2025
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
@STofone STofone added the topic: feature Discussions about new features for Python's type annotations label May 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

1 participant
0