为什么错误的类型提示在代码中不在调试控制台中时可以很好地工作?
我试图做的是:
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: List[List[int]] = []
t = Board(3, 4)
我像这样输错了。
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: list[list[int]] = [] # typo here
t = Board(3, 4)
我认为会发生错误,因为据我所知,在 python 3.9 中引入了使用类型(列表、元组、字典...)作为类型提示,而我正在使用 3.7.4。但相反没有发生错误。觉得这很奇怪,所以我尝试了这个:
a: list[int] = [0]
并且......
类型错误:“类型”对象不可订阅
这是我在输入错误时所期望的(列表->列表)。我在原始代码中放置了一个断点:
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: list[list[int]] = []
... # breakpoint here
t = Board(3, 4)
并在调试控制台中...
self.layout: list[list[int]] = []
发生了同样的错误。
类型错误:“类型”对象不可订阅
问题:如果在我的 python 版本 (3.7.4) 中不允许使用 'list' 作为类型提示,为什么我的原始代码运行时没有错误?
谢谢。
附:也许这更奇怪......
from typing import List
class Test():
def __init__(self):
a: list[int] = [0] # it works as a = [0]
if __name__ == "__main__":
t = Test()
b: list[int] = [0] # TypeError occurs. Why?
What I tried to do was:
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: List[List[int]] = []
t = Board(3, 4)
and I mistyped like this.
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: list[list[int]] = [] # typo here
t = Board(3, 4)
I thought an error would occur because to my knowledge using types(list, tuple, dict, ...) as type hints is introduced in python 3.9 and I'm using 3.7.4. But on contrary no error occurred. Thought it's weird so I tried this:
a: list[int] = [0]
and...
TypeError: 'type' object is not subscriptable
which I expected at first when I made typo (List->list). I put a breakpoint in the original code:
from typing import List
class Board():
def __init__(self, width, height):
self.width = width
self.height = height
self.layout: list[list[int]] = []
... # breakpoint here
t = Board(3, 4)
and in debug console...
self.layout: list[list[int]] = []
same error occurred.
TypeError: 'type' object is not subscriptable
Question: If using 'list' as type hints is not allowed in my python version (3.7.4), why did my original code run without errors?
Thank you.
ps. maybe this is weirder...
from typing import List
class Test():
def __init__(self):
a: list[int] = [0] # it works as a = [0]
if __name__ == "__main__":
t = Test()
b: list[int] = [0] # TypeError occurs. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 类型注释的运行时效果:
From Runtime Effects of Type Annotations: