'Python type hinting: custom data type

Let say, I want to have a custom type that I call Size. Fundamentally, this type is nothing more than an int.

However, I would like to have the following behaviour:

some_size: Size = 42
not_a_size: int = 12

>>> isinstance(some_size, int)
True

>>> isinstance(some_size, Size)
True

>>> isinstance(not_a_size, int)
True

>>> isinstance(not_a_size, Size)
False

Defining a type alias: Size = int is possible, but isinstance(not_a_size, Size) would return True. I also explored TypeVar (Size = TypeVar('Size', bound=int)) but it is not made for this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source