Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python raises exception 'generator' object does not support item assignment instead of 'generator' object is not subscriptable

This is a question I am asking only out of curiosity.

I answered this question about generators, and the exception that got raised surprised me. I would expect both of these to give the same exception:

# 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

I would expect both of them to raise a TypeError with the message "'generator' object is not subscriptable", because it seems to be more important. Why give the message that you can't assign, whenever trying to access an element would already raise an exception?

Not sure if this is relevant, but I'm using Python 3.3.

like image 202
Cody Piersall Avatar asked Jun 26 '26 14:06

Cody Piersall


1 Answers

Those two operations invoke different methods; accessing a subscript invokes __getitem__(), whereas setting a subscript invokes __setitem__(). Each raises a different exception because each is a different operation conceptually.

like image 55
Ignacio Vazquez-Abrams Avatar answered Jun 28 '26 03:06

Ignacio Vazquez-Abrams