Search code examples
pythonpycharmpython-typing

Type hinting Python class with dynamic "any" attribute


I have a Python class that supports "any" attribute through dynamic attribute resolution. This is one of the flavours of "attribute dict" pattern:

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

How can I tell Python type hinting that this class supports dynamic looking of attributes?

If I do

value = my_attribute_dict.my_var

Currently, PyCharm and Datalore are complaining:

Unresolved attribute reference 'my_var for class 'MyAttributeDict'

Solution

  • Based on the comment of user sudden_appearance, adding a dummy __getattribute__ solves the problem:

    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)