Type variables or generics,Allow us to write flexible, reusable code by creating placeholder types that can that can stand for different types and different contexts。Especially in classes and functions。
The author used the TypeVar from Python's typing module。
from typing import TypeVar, Generic
#T can be any type
T = TypeVar("T")
#N can be int or float
N = TypeVar("N", int, float)
Since float can handle int in python ,N = TypeVar("N", int, float),"int"in the code is redundant?
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.0
By inheriting from the Generic class, and specifying a particular type, you can create subclasses that work with specific data types.
Let's consider an example involving a generic class Box that holds a single item of any type. We then create subclasses of Box that are specific to certain data types.
First, let's define the generic class Box:
from typing import TypeVar, Generic
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self, item: T):
self.item = item
def get_item(self) -> T:
return self.item
In the code above, Box is a generic class parameterized by T. It can hold an item of any type.
Now let's create a few subclasses that inherit from Box and are specific to certain data types:
class IntBox(Box[int]):
pass
class StrBox(Box[str]):
pass
class FloatBox(Box[float]):
pass
Now, these subclasses IntBox, StrBox, and FloatBox are specialized versions of the Box class that are designed to work with int, str, and float types, respectively.