Search code examples
pythonpython-3.xlistgenericssubclass

Python subclass list of generic type T


I'm trying to subclass list of generic type T. Right now, I'm able to achieve what I want with multiple inheritance with Generic and list as shown below. Is there a better way to achieve the same?

from typing import TypeVar, Generic

T = TypeVar('T')

class SuperList(Generic[T], list):
    def __init__(self, *args: T):
        super().__init__(args)
 
    def really_awesome_method(self):
        ...

class A(SuperList[int]):
    pass

class B(SuperList[str]):
    pass


Solution

  • I think it's new in 3.9, but you can subscript many builtin containers to create generic type aliases. So you should be able to just do:

    class SuperList(list[T]):
        def __init__(self, *args: T):
            super().__init__(args)
    
    class A(SuperList[int]):
        pass
    

    https://docs.python.org/3/library/stdtypes.html#types-genericalias