Generics, classes and instances

Viewed 36

Is there any concept where I can combine generics and outline a relationship between classes and instances of that class?

A bit of a contrived example, but it get my point across:

ManagedClass = TypeVar("ManagedClass")


class MyClass1:
   def my_method(self):
      ...


def instantiate_class(cls: ManagedClass, *args, **kwargs) -> ManagedClass:
    return cls(*args, **kwargs)

myclass1 = instantiate_class(MyClass1)

myclass1.my_method()  # IDE Warning: Parameter 'self' unfulfilled

The warning is obviously correct, but not what I am after.

Is there any way to provide this concept to type checkers, where the input type is a class and the return type is an instance of that class?

1 Answers

You want something like this:

def instantiate_class(cls: Type[ManagedClass], *args, **kwargs) -> ManagedClass:
    ...

For further illustration:

# Type an instance of a class:
foo: Foo = Foo()

# Type a class itself:
foo: Type[Foo] = Foo
Related