1 year ago

#386853

test-img

gvr

What is the correct way to annotate types of an injected dependency in Python

Could anyone enlighten me as to the best way to type-annotate an injected dependency in Python such that a member is correctly identified by the type-hinting of an IDE?

Take the following example:

class Type: pass


class Type1(Type):
    def __init__(self, value):
        self.some_member = value


class Type2(Type):
    def __init__(self, value):
        self.other_member = value


class Base:
    def __init__(self, injected: Type):
        self.injected = injected


class Derived1(Base):
    def __init__(self, injected: Type1):
        super().__init__(injected)


class Derived2(Base):
    def __init__(self, injected: Type2):
        super().__init__(injected)

What I would like is for the IDE (VS Code/PyCharm etc.) to be able to provide type hinting support when accessing the members of the injected dependency:

instance1 = Derived1(Type1(5))
instance1.injected.some_member = 2  # IDE knows nothing about `some_member`

The docs imply the best way to address this would be using TypeVar

MyType = TypeVar('MyType', bound=Type)

class Base:
    def __init__(self, injected: MyType):
        self._injected = injected

This unfortunately doesn't help. Any suggestions greatly appreciated.

Note that the linter itself is perfectly happy with the usage, so this seems more like a possible limitation of the type-hinting introspection in the IDE.

python-3.x

annotations

0 Answers

Your Answer

Accepted video resources