This appears to be similar to Type Hinting: Argument Of Type Class, however, the accepted answer there does not actually answer my question, so perhaps the question was expressed incorrectly (?)
I have a serialization/deserialization framework that would benefit greatly from [IDE-supported] type hinting. The API looks something like this:
def serialize(obj:BaseModel) -> Dict[str,Any]: """ Serialize the object to a dictionary. """ def deserialize(data:Dict[str,Any], clazz:type) -> BaseModel: """ Deserialize dictionary into a model object of type clazz. """
The serialization method is fine, but deserialize type hinting is not optimal. I want to indicate that the return value of deserialize will be an object of type clazz
(which is a subclass of BaseModel
). This seems like something that generics could help with, but I’m not sure how to express what I want.
T = TypeVar('T', bound=BaseModel) def deserialize(data:Dict[str,Any], clazz:T) -> T: """ Deserialize dictionary into a model object of type clazz. """
This seems wrong since, clazz is a class derived from T not an object (instance) of type T.
I’ve done some reading but haven’t found an answer (it’s also tricky to google this particular problem). Is there something obvious I’m missing here or is this just not supported by the python 3.5 typing module?
Granted, that I’m still at the mercy of my tooling to infer types, but hopefully if there is a correct way to do this it will be implemented by the type-checking utilities.
Advertisement
Answer
Since a class can be thought of as a callable that returns and instance of itself, maybe you could try:
T = TypeVar('T', bound=BaseModel) def deserialize(data: Dict[str, Any], clazz: Callable[..., T]) -> T: """ Deserialize dictionary into a model object of type clazz. """
The ellipsis (...
) means the call signature of the class is unspecified. So a callable object that takes unspecified arguments and returns an instance of T
.