3.11. Typing Alias
Since Python 3.12 you can use
typesoft-keyword to define type aliasesSince Python 3.12 PEP 695 - Type Parameter Syntax
3.11.1. Problem
>>> class List:
... data: list
...
... def __init__(self):
... self.data = []
...
... def append(self, item):
... self.data.append(item)
...
... def remove(self, item):
... self.data.remove(item)
>>> class List:
... data: list[int]
...
... def __init__(self):
... self.data = []
...
... def append(self, item: int):
... self.data.append(item)
...
... def remove(self, item: int):
... self.data.remove(item)
3.11.2. Type Generic
class List[T]- type generic
>>> class List[T]:
... data: list[T]
...
... def __init__(self):
... self.data = []
...
... def append(self, item: T):
... self.data.append(item)
...
... def remove(self, item: T):
... self.data.remove(item)
>>>
>>>
>>> mylist: List = List()
>>> mylist.append(1) # ok
>>> mylist.append(2.0) # ok
>>> mylist.append('three') # ok
>>>
>>> mylist: List[int] = List()
>>> mylist.append(1) # ok
>>> mylist.append(2.0) # error
>>> mylist.append('three') # error
>>>
>>> mylist: List[int|float] = List()
>>> mylist.append(1) # ok
>>> mylist.append(2.0) # ok
>>> mylist.append('three') # error
>>>
>>> mylist: List[int|float|str] = List()
>>> mylist.append(1) # ok
>>> mylist.append(2.0) # ok
>>> mylist.append('three') # ok
3.11.3. Type Generic with Constraints
class List[T: (int,float)]- type generic with constraints
>>> class List[T: (int,float)]:
... data: list[T]
...
... def __init__(self):
... self.data = []
...
... def append(self, item: T):
... self.data.append(item)
...
... def remove(self, item: T):
... self.data.remove(item)
>>>
>>>
>>> mylist: List = List() # ok
>>> mylist: List[int] = List() # ok
>>> mylist: List[int|float] = List() # ok
>>> mylist: List[int|float|str] = List() # error