NameError: name 'List' is not defined

问题

环境:python3.8
代码:在leetcode本地vs code运行时候报错。NameError: name 'List' is not defined

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

原因

经过查询相关的资料,发现只需要在头部导如typing模块就行了。

from typing import List

typing模块

python是一门弱类型的语言,使用过程不用过多关注变量的类型,但是同时也带来了问题,就是代码的易读性变差了,有时候自己都不知道传入的是什么参数。因此在python3.5之后,引入了一个typing模块,这个模块可以很好解决这个问题。

函数接受并返回一个字符串,注释像下面这样:

def greeting(name: str) -> str:
    return 'Hello ' + name

在函数 greeting 中,参数 name 预期是 str 类型,并且返回 str 类型。子类型允许作为参数。

typing模块的作用

  • 类型检查,防止运行时出现参数和返回值类型不对的情况
  • 作为开发文档附加说明,方便使用函数时传入和返回正确的参数,利于开发效率
  • 该模块并不会实际影响到程序的运行,不会报错,但是会有提示。

typing常用类型

  • int,long,float: 整型,长整形,浮点型;

  • bool,str: 布尔型,字符串类型;

  • List, Tuple, Dict, Set:列表,元组,字典, 集合;

  • Iterable,Iterator:可迭代类型,迭代器类型;

  • Generator:生成器类型;

注意:迭代器中的元素可能是多种类型,使用or或union操作符

参考:
https://www.jianshu.com/p/cec576f23667
https://docs.python.org/zh-cn/3.8/library/typing.html?highlight=typing#module-typing

原文地址:https://www.cnblogs.com/easonbook/p/12876402.html