具有动态“any”属性的类型提示 Python 类

问题描述 投票:0回答:1

我有一个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'
python pycharm type-hinting
1个回答
0
投票

根据 Reinderien 的评论,添加一个虚拟对象

__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)

© www.soinside.com 2019 - 2024. All rights reserved.