Search code examples
pythonpython-typing

How to check if a type is in a TypeVar or not


I am looking for a way to check (True or False) if a type exist in a TypeVar:

from typing import TypeVar 
number = TypeVar("number" ,int ,float)

num: number = 3.14

I am looking for sth like this:

 print(type(num) in number) # check if "float" is in "number"

Solution

  • The constraints of a type variable is stored as a tuple in the __constraints__ attribute according to the documentation, so you can simply perform the following check:

    type(num) in number.__constraints__