4 ms·
what's the difference between list and List, dict and Dict and Mapping?
by singularity2001 8y ago
what's the difference between list and List, dict and Dict and Mapping?
- lou1306 8y agoList, Dict can be enriched with the type of objects they contain: e.g. List[int] or Dict[str, str]. Mapping is a type hint for any object that implements the __getitem__ magic method (i.e. you can do `foo[bar]`).
- ubernostrum 8y agoSuppose you want to indicate that a particular variable is a list of int. You might write "list[int]" to indicate that. But try that in a Python interpreter and you'll get an error -- "list[int]" attempts to subscript the list class object, which doesn't work. So typing.List exists to be a subscriptable object you can use when annotating, and "typing.List[int]" works. Same for the other names.
- singularity2001 8y agoThanks, I tried, and indeed: 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?
- ubernostrum 8y agoThe 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.