Python type hinting - have hint return type of class not instance of given class

Viewed 187

I have a situation where I have two convenient methods for finding and initialising classes from an entry point, and I want to distinguish what they do from one another.

The following is a simplified version of my problem

class ToBeExtended:
   """ Abstract base class that is to be extended """
   pass

def find(classname: str) -> ToBeExtended:
    """ Find the class definition of the class named `classname` from the entry points """
    ... # Get the class
    return ClassDefinition

def connect(classname: str, *args, **kwargs) -> ToBeExtended:
    """ Find and initialise the class with the passed arguments and return """
    return find(classname)(*args, **kwargs)

find in this example is returning a class object, not an instance.

Is there a way to wrap this to give that context to a linter/user? There doesn't seem to be anything in typing and I'd like to have the class identifiable, nothing like -> type:

1 Answers
import typing

class ToBeExtended:
   """ Abstract base class that is to be extended """
   pass

def find(classname: str) -> typing.Type[ToBeExtended]:
    """ Find the class definition of the class named `classname` from the entry points """
    ... # Get the class
    return ClassDefinition

def connect(classname: str, *args, **kwargs) -> ToBeExtended:
    """ Find and initialise the class with the passed arguments and return """
    return find(classname)(*args, **kwargs)
Related