Search code examples
pythontype-hinting

How to annotate a user-defined collection in Python?


I've created a collection type:

from collections.abc import Sequence

class MyCollection(Sequence):
    pass

and I want to annotate object of my class like this:

obj: MyCollection[int] = MyCollection()

How to achieve this?

I wrote:

obj: MyCollection[int] = MyCollection()

But IntelliSense only specifies MyCollection not MyCollection[int].


Solution

  • You could use typing it provides runtime support for type hints, for user-defined generic collection, you can use typing.Generic and typing.TypeVar

    Here is an example:

    from typing import TypeVar, Generic
    from collections.abc import Sequence
    
    T = TypeVar('T')
    
    class MyCollection(Sequence, Generic[T]):
        def __init__(self):
            self.data = []
    
        def __getitem__(self, index):
            return self.data[index]
    
        def __len__(self):
            return len(self.data)
    
        def add(self, item: T):
            self.data.append(item)
    
    obj: MyCollection[int] = MyCollection()
    obj.add(1)