2007-09-15

What would happen if we removed slicing/indexing syntax support?

I just finished reading (at least the parts that interested me) the paper 'An Overview of the Scala Programming Language'. As with most language papers I write, I read it from the perspective of a Python developer looking for new ideas to steal.

While nothing really leapt out at me (Scala is big into types and most of its interesting features ties into that), one thing that I thought was interesting is how there is no special syntactic support for array access in Scala; you don't use ``spam[42]``, but ``spam(42)``. It's an interesting idea and it is portable to Python.

Imagine that instead of having slicing/indexing support in the grammar, things such as lists, tuples, and dicts had their current __getitem__ method bound to __call__ instead. While odd, it is not totally a ridiculous thing to consider. By removing that piece of syntactic reliance you could know pass methods and functions to places where duck typing only calls for indexing. But as it stands now you can't do that unless you tack on a __getitem__ method to the object or catch the TypeError and then try calling the object.

You could even take this further and ditch the list and tuple literals syntax. ``[1,2,3]`` could, if list's constructor came to have arbitrary positional arguments, to be ``list(1,2,3)`` (you would need to change calls like ``list("abc")`` to be more like ``list(*"abc")`` in order to allow for this kind of instantiation). This would allow one to override the built-in list type with whatever one wanted and be guaranteed that all lists were constructed using your type. This could extend to tuples as well (dicts would be a pain because of their pairing nature and if tuple/list syntax support was gone that would get unwieldy very quickly without a cons type). This would hurt performance, though, as the literal syntax allows for list creation opcodes. And list comprehensions would just be replaced by generator expressions passed to the list type.

While I don't think getting rid of literal syntax for the buit-in types is good, it might not totally suck to ditch index/slice syntax support for making the built-in types callable. But then this has no chance of happening until Python 4 and who the hell knows when that would happen.