4 ms·
The exact error you're going to get in a modern Python is: TypeError: 'type' object is not subscriptable That's because "list" refers to the class object,
by ubernostrum 8y ago
The exact error you're going to get in a modern Python is:
TypeError: 'type' object is not subscriptable
That's because "list" refers to the class object, which is not an instance of list; it's an instance of type. Implementing __getitem__ on list (which is already implemented!) will not help. Try it yourself:
class MyClass:
def __getitem__(self, key):
return f"You asked for {key}"
Now try "MyClass[int]". You'll get the same error: "TypeError: 'type' object is not subscriptable". Class objects in Python are instances of type, so __getitem__ would have to be implemented on type in order to make this work. Which would in turn make it work on any type in Python, not just those which are supposed to represent collections/mappings.
The typing module's solution of sentinel objects to stand in for collection/mapping types, supporting subscripting for annotating the types of contents, is probably a better solution.
- singularity2001 8y agoUnderstood. They could just allow __getitem__ on types to avoid semantic duplications.