what's the difference between list and List, dict and Dict and Mapping?
So typing.List exists to be a subscriptable object you can use when annotating, and "typing.List[int]" works. Same for the other names.
list[int] TypeError: 'type' object has no attribute '__getitem__'
couldn't they just implement __getitem__ on the existing list class instead of creating semantic duplication?
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.
Mapping is a type hint for any object that implements the __getitem__ magic method (i.e. you can do `foo[bar]`).