pythoncastingpython-typing

How to properly use type hints in Python?


I can't figure out how to properly use type hints in my type_casting function.

def type_casting(var, _type):
    if _type not in (str, int, float, bool):
        return Exception

    return _type(var)

assert type_casting("55", int) == 55
assert type_casting(55, str) == "55"

How to properly use type hints in Python?

I want to do something like this:

T = int | float | str | bool
def type_casting(var: Any, _type: Type[T]) -> T:

Solution

  • You can use Any and TypeVar

    from typing import TypeVar, Type, Any
    
    T = TypeVar('T', int, float, str, bool)
    
    def type_casting(var: Any, _type: Type[T]) -> T:
        if _type not in (str, int, float, bool):
            raise ValueError(f"Unsupported type {_type}")
    
        return _type(var)
    

    You can reference here TypeVar