最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Descriptor type hints - Stack Overflow

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论