caeser 发表于 2023-3-15 17:27:05

函数的类型注释报错

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def times(s:list, n:int = 5) -> list:
        pass

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
    def times(s:list, n:int = 5) -> list:
TypeError: 'type' object is not subscriptable
>>>

请问各位老师,这是什么原因?是不是版本的原因?

isdkz 发表于 2023-3-15 17:29:23

这个错误是因为在 Python 3.8.5 版本中,要使用类型提示(如 list),你需要从 __future__ 模块中导入 annotations。

这个特性在 Python 3.9 版本中已经成为默认行为,但在较早的版本中,你需要手动导入。请尝试在代码开头添加以下导入语句:

from __future__ import annotations

修改后的代码应该如下:

from __future__ import annotations

def times(s: list, n: int = 5) -> list:
    pass

这样应该可以解决你遇到的问题。
页: [1]
查看完整版本: 函数的类型注释报错