'Python type hinting for class factories

Consider the following code:

class A(): pass

class B(A): 
    def bar(self): pass

T = TypeVar("T", bound=A)

def C(cls: type[T]):
    class _C:
        def __init__(self): 
            self.foo = cls()
    return _C
    
D = C(B)
D().foo.bar

Pylance infers the type of D().foo as just T, and hence complains that bar doesn't exist. What can I do to have D carry the information that every instance of D uses B?

Also, I'm not sure if this is relevant, but I noticed that when I write the following, Pylance correctly infers that D().foo is of type B, but still complains because it we assign cls() of type T to a variable of type S.

def C(cls: type[T]):
    class _C(Generic[S]):
        def __init__(self): 
            self.foo: S = cls()
    return _C[cls]

(Disclaimer: A previous version of this question was posed inaccurately and closed.)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source