Cody Piersall
Cody Piersall

Reputation: 8557

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.

Upvotes: 3

Views: 2707

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799430

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.

Upvotes: 4

Related Questions