【发布时间】:2013-12-06 18:56:27
【问题描述】:
我只是出于好奇才问这个问题。
我回答了this question 关于生成器的问题,引发的异常让我感到惊讶。我希望这两个都会给出相同的例外:
# Create a lame generator
a = (x for x in range(5))
# This raises a TypeError with the message "'generator' object is not subscriptable"
# I completely expected this.
a[0]
# Why doesn't this give the same message?
# This raises a TypeError with the message "'generator' object does not support item assignment"
# which is (I think) the exception raised when trying to assign to an immutable object.
a[0] = 2
我希望他们两个都会引发 TypeError 并显示消息“'generator' object is not subscriptable”,因为它似乎更重要。为什么要给出您无法分配的消息,无论何时尝试访问一个元素都会引发异常?
不确定这是否相关,但我使用的是 Python 3.3。
【问题讨论】:
标签: python exception generator