对具有动态“任何”属性的Python类进行类型提示

1 投票
1 回答
56 浏览
提问于 2025-04-12 23:42

我有一个Python类,它可以通过动态属性解析来支持“任何”属性。这是“属性字典”模式的一种变体:

class ReadableAttributeDict(Mapping[TKey, TValue]):
    """
    The read attributes for the AttributeDict types
    """

    def __init__(
        self, dictionary: Dict[TKey, TValue], *args: Any, **kwargs: Any
    ) -> None:
        self.__dict__ = dict(dictionary)  # type: ignore

我该如何告诉Python的类型提示,这个类支持动态查找属性呢?

如果我这样做:

value = my_attribute_dict.my_var

目前,PyCharm和Datalore都在抱怨:

Unresolved attribute reference 'my_var for class 'MyAttributeDict'

1 个回答

0

根据用户 sudden_appearance 的评论,添加一个虚假的 __getattribute__ 方法可以解决这个问题:

class ReadableAttributeDict(Mapping[TKey, TValue]):

    def __getattribute__(self, name):
        # Only implemented to make type hinting to stop complaining
        # Default behaviour
        # https://stackoverflow.com/a/2405617/315168
        return object.__getattribute__(self, name)

撰写回答