Search code examples
pythontype-hinting

Python's equivalence of Typescript's indexable type?


In typescript, there is a construct called index signature that let me, for instance, express that all properties of a particular object have values of type string, i.e:

type Foo = { [key: string]: string }

How do I type hint something similar in Python, e.g express that all attributes of a class should have values of type string? The reason I want to do this because I have a Python class whose attributes are not known in advance, but are set dynamically.


Solution

  • The equivalent of your Foo type would be a dict with keys and values that both have type str:

    Foo = dict[str, str]
    

    If you're generating attributes on a custom class dynamically via __getattr__, the signature of __getattr__ determines the type of the attributes:

    class Foo:
        def __getattr__(self, name: str) -> str:
            return "foo"
    
    f = Foo()
    reveal_type(f.bar)  # note: Revealed type is "builtins.str"