Skip to content
Advertisement

How to add Python type hints to runtime type

How would you add type hints to this function?

def cast_to(x, ty=bool):
    return ty(x)

Advertisement

Answer

Hmm it seems you can do it like this:

from typing import Type, TypeVar, Any

T = TypeVar('T')

def cast_to(x: Any, ty: Type[T] = bool) -> T:
    return ty(x)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement