"TypeError: 'type' object is not subscriptable" in a function signature "TypeError: 'type' object is not subscriptable" in a function signature python-3.x python-3.x

"TypeError: 'type' object is not subscriptable" in a function signature


The expression list[int] is attempting to subscript the object list, which is a class. Class objects are of the type of their metaclass, which is type in this case. Since type does not define a __getitem__ method, you can't do list[...].

To do this correctly, you need to import typing.List and use that instead of the built-in list in your type hints:

from typing import List...def twoSum(self, nums: List[int], target: int) -> List[int]:

If you want to avoid the extra import, you can simplify the type hints to exclude generics:

def twoSum(self, nums: list, target: int) -> list:

Alternatively, you can get rid of type hinting completely:

def twoSum(self, nums, target):


The answer given above by "Mad Physicist" works, but this page on new features in 3.9 suggests that "list[int]" should also work.

https://docs.python.org/3/whatsnew/3.9.html

But it doesn't work for me. Maybe mypy doesn't yet support this feature of 3.9.