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

陌路散爱 提交于 2021-02-16 14:00:48

问题


Why am I receiving this error when I run this code?

Traceback (most recent call last):                                                                                                                                                  
  File "main.py", line 13, in <module>                                                                                                                                              
    def twoSum(self, nums: list[int], target: int) -> list[int]:                                                                                                                    
TypeError: 'type' object is not subscriptable
nums = [4,5,6,7,8,9]
target = 13

def twoSum(self, nums: list[int], target: int) -> list[int]:
        dictionary = {}
        answer = []
 
        for i in range(len(nums)):
            secondNumber = target-nums[i]
            if(secondNumber in dictionary.keys()):
                secondIndex = nums.index(secondNumber)
                if(i != secondIndex):
                    return sorted([i, secondIndex])
                
            dictionary.update({nums[i]: i})

print(twoSum(nums, target))

回答1:


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):



回答2:


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.



来源:https://stackoverflow.com/questions/63460126/typeerror-type-object-is-not-subscriptable-in-a-function-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!