Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typing - return value is instance of parameter

I have a function that receives a class and returns an instance of that class. A simple example:

def instantiate(class_: Type[enum.Enum], param: str) -> enum.Enum:
    return class_(param)

The return value is the same as the type of the parameter class_, so if class_ is MyEnum, the return value will be of type MyEnum.

Is there some way to declare that?

like image 251
user972014 Avatar asked Apr 13 '26 11:04

user972014


1 Answers

There sure is! This should work perfectly for your use case.

from enum import Enum
from typing import TypeVar, Type


E = TypeVar('E', bound=Enum)


def instantiate(class_: Type[E], param: str) -> E:
    return class_(param)

And to just do a quick test of it to confirm that type hinting is working as intended:

class MyEnum(Enum):
    ONE = '1'
    TWO = '2'


# I hover over 'e' and PyCharm is able to infer it's of type MyEnum.
e = instantiate(MyEnum, '1')

print(e)
# MyEnum.ONE

Note: As mentioned in comments, in Python 3.9, some typing constructs like Type, List, and Dict are deprecated, as you can just use the builtin types. So the above annotation could be defined like type[E] if you have a newer Python version.

like image 86
rv.kvetch Avatar answered Apr 15 '26 00:04

rv.kvetch