简体   繁体   中英

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

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM