SliceSuffix is inconsistent
The spec defines
SliceSuffix = '[' [Expression] ':' [Test] [':' [Test]] ']'
| '[' Expression ']'
.
Expression = Test {',' Test} .
This would imply that the following is a valid Starlark program
a = {}
a[1,2:3] = "foo"
print(a)
When running this program in Python, the output is the following
{(1, slice(2, 3, None)): 'foo'}
When running the same program in Bazel, the output is the following error
cannot assign to 'a[(1, 2):3]'
There are the following aspects around the current syntax:
- In Python parses this as a tuple with the first element an int and the second a slice. Starlark is a slice with the first element a tuple and the second an int.
- If Bazel does not allow setting a value to a dict with the key being a slice (making the assumption that the previous point was intentional), why is the syntax not
'[' [Test] ':' [Test] [':' [Test]] ']'? Is there some other case that the generality of the syntax is needed?
Thanks for spotting this ambiguity. I can't repro in Python 3.11.9 because it complains that slices aren't hashable, but inspecting the tree obtained from ast.parse('a[1,2:3]') confirms it's a tuple who second item is a slice.
Personally I'd be in favor of banning this example as ambiguous / likely to cause confusion. Unlike Python, the Starlark concept of a slice is just a syntactic construct, not a reified runtime object, and I don't think the Python behavior can even be expressed without changing that.
It sounds like this is resolved by changing Expression to Test as you suggest. @adonovan, any concerns?
The code in the original comment was tested with Python 3.13.1 on MacOS, and works as stated there. In this version of Python, it does not run into the issue present at https://github.com/bazelbuild/starlark/issues/291#issuecomment-2552252859