Search code examples
pythontype-hintingtyping

Set typehint for custom subclass of List - TypeError: 'type' object is not subscriptable


I am trying to specify the elements of a returned List subclass via typehinting.

from typing import Union, List, Tuple, Optional, NewType
from jira import JIRA
from jira.client import ResultList
from jira.resources import Issue

def search(...) -> ResultList[Issue]: # using 'List[Issue]:' or 'ResultList:' as return type hint work
    ...

However, I am running in this error:

TypeError: 'type' object is not subscriptable

I've tried my luck with NewType, but cannot get it to run as expected. When not specifying the subclass ResultList[Issue] and using List[Issue] instead, it works. Also, when not mentioning the element type by simply using ResultList, it works.

Additional information:

ResultList Code

Issue Code


Solution

  • you should look at these:

    explanation:
    list and typing.List are totally different things
    in order to utilize generic you must inherit from typing.Generic
    if you use third party libs code and cant make changes to ResultList, then stubs is a solution
    basically you need to define stub for ResultList class in *.pyi file like this:

    from typing import Generic, TypeVar, Iterable
    
    T = TypeVar('T')
    
    class ResultList(list, Generic[T]):
        def __init__(
            self, iterable: Iterable[T] = ..., _startAt: int = ..., _maxResults: int = ..., _total: int = ..., _isLast: bool = ...
        ) -> None:
            ...
        ...
    

    after that you can use as typing as follows:

    from unittest import TestSuite
    
    from res import ResultList
    
    
    class SomeClass:
        pass
    
    
    def foo() -> 'ResultList[int]':
        return ResultList(iterable=[SomeClass()])
    
    
    if __name__ == '__main__':
        a: 'ResultList[str]' = foo()
    # pycharm will highlight "unexpected type error"
    

    dont forget to connect stubs in pycharm as it showed in link