[Python] How to annotate dict-like object with key-value structure in Python?

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say that I have a class like:

    from typing import Any

    class A:
    def __init__(self, *args):
    self.items: list[int] = list(args)

    def __getitem__(self, k: str):
    v = int(k)
    if v in self.items:
    return v
    return None

    def __setitem__(self, k: str, _: Any = None):
    v = int(k)
    print(f'Value {_} is not important')
    if v not in self.items:
    self.items.append(int(k))


    Elements of the class are accessible by object[element_name] syntax. And it is obvious that value of element will be an integer:

    a = A(1, 2, 3)
    a['4'] = 'Something'

    print(a['2'])
    # 2
    print(a['4'])
    # 4


    Annotation for a dictionary with the same behavior will be like dict[str, int]. Where key is str and value is int. But how to annotate these generic types for custom objects?

    Because A[str, int] is not working.

    Continue reading...

Compartilhe esta Página