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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With