简体   繁体   中英

Python Annotation in 3.9 listed as NameError

Recently I've been using leetcode to learn Python, and one of the questions has a class and a function definition as starter code like so:

Class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

However, when I try to write my solution in my own IDE, it gives me the following error:

~/VSCode/Python  /usr/bin/python3.9 /home/dozydoh/VSCode/Python/test.py
Traceback (most recent call last):
  File "/home/dozydoh/VSCode/Python/test.py", line 1, in <module>
    class Solution:
  File "/home/dozydoh/VSCode/Python/test.py", line 2, in Solution
    def twoSum(self, nums: List[int], target: int) -> List[int]:
NameError: name 'List' is not defined

I upgraded to Python 3.9 but still receive the same error. Why is the annotation being interpreted like this? I thought it would be only used by 3rd libraries or something along those lines.

TIA

You are right that it is supported, but as I wrote in my comment, you need to import this name.

You can do that via:

from typing import List


# Rest of code
# ...

More info can be found here: https://docs.python.org/3/library/typing.html .

In 3.9 you can also use types themselves in annotations. eg:
def twoSum(self, nums: list[int], target: int) -> list[int]:

This means you won't have to import List from typing

This is described in What's New In Python 3.9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM