Python Forum

Full Version: making : optional
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
what would be an example of a situation where code can be valid without : and valid with : and have different semantics? or can a language like Python that has optional : be possible?

if i leave out : i get a syntax error. is there a case where that does not happen?
>>> L = list(range(10))
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> L[:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> L[-1]
9
If there is a colon in the square brackets, it's an instance of slice.
A slice takes 3 arguments. [::] -> slice(None, None, None)

[::-1] -> slice(None, None, -1)
The : in the subscription is like a comma in the function call.
If you use a comma in the subscription, then the key is a tuple.


You can try it by yourself.
__class_getitem__ was introduced for typehints.
I used it because then I don't have to create an instance of the class.
It's like __getitem__ for instances.

class GetItem:
    def __class_getitem__(self, key):
        if isinstance(key, slice):
            print("Key is a slice")
        elif isinstance(key, tuple):
            print("Key is a tuple")
            if all(isinstance(item, slice) for item in key):
                print("All items are slices")
            elif any(isinstance(item, slice) for item in key):
                print("One or more items are a slice instance")
        else:
            print("Got something else")
        return key
        



print(GetItem[1])
print(GetItem[:])
print(GetItem[0:])
print(GetItem[1:3])
print(GetItem[:2])
print(GetItem[::-1])
print(GetItem[:,1,:])
i didn't think about slices although a different language could require tuples be inside () and use , in place of : in the square brackets. i was thinking about the : that follow keywords like def, if, else, for, while, try. except ... well, eventually follow. what if that language looked like:
class GetItem
    def __class_getitem__(self, key)
        if isinstance(key, slice)
            print("Key is a slice")
        elif isinstance(key, tuple)
            print("Key is a tuple")
            if all(isinstance(item, slice) for item in key)
                print("All items are slices")
            elif any(isinstance(item, slice) for item in key)
                print("One or more items are a slice instance")
        else
            print("Got something else")
        return key
...