4 ms·
Suppose 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
by ubernostrum 8y ago
Suppose 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.