Search code examples
pythonpython-typingpyright

Static colored attributes on custom types without adding them in class definition in python


I would like to have a custom type whose attributes are highlighted statically in IDE (for auto-completion & error highlighting), e.g, VSCode, without explicitly adding them at class definition. For example:

from typing import NamedTuple

class Foo(NamedTuple):
    bar: int

class MyDict:
    def __init__(self, n: NamedTuple) -> None:
        self._n = n

    def __getattr__(self, key: str) -> int:
        return getattr(self._n, key)

foo = Foo(3)
bar = foo.bar  # `bar` is colored in Vscode

x = MyDict(foo)
y = x.bar  # `bar` is not colored in Vscode (no autocompletion either)

Is there a way to achieve this highlighting statically on custom types? Thanks.


Solution

  • I came up with a satisfying solution for my use case:

    from typing import Generic, NamedTuple, TypeVar
    
    T = TypeVar("T", bound=NamedTuple)
    
    class Foo(NamedTuple):
        bar: int
    
    class MyDict(Generic[T]):
        @property
        def inputs(self) -> T:
            ...
    
    foo = Foo(3, 4)
    bar = foo.bar  # `bar` is colored in Vscode
    
    x = MyDict[Foo]()
    x.inputs.bar  # `bar` is colored in Vscode
    

    Not sure there is a way to accomplish this directly for x.bar though.