Type variables(generics)
from typing import TypeVar, Generic
#T can be any type
T = TypeVar("T")
#N can be int or float
N = TypeVar("N", int, float)
Python's type system treats `int` and `float` as distinct types, even though a float can represent an integer value. So, even though it's true that floats can handle integers, it's not redundant to define a `TypeVar` that allows both `int` and `float`. It indicates to the type checker (and to other programmers) that a function or class that uses `N` is designed to work with both integers and floating-point numbers.
While a float in Python can represent an integer value (like `3.0`), an int can't fully represent a float. If you attempt to assign a floating-point value to an integer, Python will truncate the decimal part, leading to loss of information.
>>> int(3.5)
3
>>> float(3)
3.0Last updated