[Python] Descriptor type hints

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use type hints in my code but I simply don't understand how the concept applies to a Python descriptor. The only relevant info I could find on the matter was this 6+ year old post but I can't get my head around the solution. Is it not common practice to use type hints for Python descriptors?

    My descriptor is pretty basic:

    class D:

    def __init__(self, a: str):
    self._a = a

    def __get__(self, instance, owner) -> str:
    return self._a

    def __set__(self, instance, a: str):
    self._a = a


    Descriptor use:

    class A:

    d = D("Hi")

    def __init__(self):
    ...


    What would be the correct type hinting for instance and owner if all instances of class D will be created in class A? Do I need to create 3 __get__ methods with @overload in my descriptor (as in the linked post) to cover different use cases of the descriptor?

    And also, is importing TypeVar and/or Generic from typing necessary? I'm also wondering if classes D and A are properly defined if they need some sort of argument from TypeVar/Generic.

    Continue reading...

Compartilhe esta Página