Range objects are created quite frequently, but doing so currently requires a name lookup and function call, whereas with syntax they could become literals - compare these two functions:
def complex_with_literal():
return 3 + 4j
def complex_without_literal():
return complex(3, 4)
Both of them return the same value. If called in a tight loop, though, the second one would have WAY more overhead. Take a look at the disassembly:
>>> dis.dis(complex_with_literal)
1 0 RESUME 0
2 2 RETURN_CONST 1 ((3+4j))
>>> dis.dis(complex_without_literal)
1 0 RESUME 0
2 2 LOAD_GLOBAL 1 (NULL + complex)
12 LOAD_CONST 1 (3)
14 LOAD_CONST 2 (4)
16 CALL 2
26 RETURN_VALUE
Your precise Python version will affect exactly how this looks, but the difference will be just as obvious. With range(1, 7)
or similar, the difference will be equally stark: a range literal would allow this to be a constant.
The advantage is somewhat weaker if there are any variables involved, but there’s still a significant benefit to be had. Consider:
def make_tuple(n):
return (n, n)
def make_diagonal(n):
return complex(n, n)
(I’ve used a tuple here because a “complex literal” is really just the imaginary part, but a tuple would be fairly similar to the way a range literal would work.)
Again, the difference here is that the constructor has to be looked up as a name. The compiler can’t optimize this because you MIGHT (highly unlikely but possible) have reassigned that name or injected a global.
With alternate lambda syntax, this isn’t the case. The existing syntax is already handled entirely by the compiler. Unless the arrow function actually has different semantics to the existing lambda syntax (like how in JavaScript there’s different behaviour around this
with arrow functions), there’s little reason to add this.
However, I would definitely recommend looking into some of the editor integrations that change how keywords like lambda
look. You may find them of value, without making any changes to the language.