[Python-ideas] More useful slices

Skip Montanaro skip.montanaro at gmail.com
Mon Feb 2 19:00:07 CET 2015


On Mon, Feb 2, 2015 at 9:29 AM, Neil Girdhar <mistersheik at gmail.com> wrote:
> This proposal is definitely *possible*, but is the only argument in
> its favor saving 5 characters?  You already have the shorthand
> exactly when you most need it (indexing).

As I indicated in an earlier response, there is some performance value
to replacing the range function call with this (or other) syntactic
sugar.  While exceedingly rare, there is nothing to prevent a
programmer from redefining the range builtin function or inserting a
different version of range() in the local or global scopes:

    def my_range(*args):
        # completely ignore args, returning something weird...
	return [1, "a", None, 2]

    import __builtin__
    __builtin__.range = my_range

If you have a for loop which uses range():

    for i in range(27):
    	do something interesting with i

optimizers like PyPy which aim to be precisely compatible with CPython
semantics must look up "range" every time it occurs and decide if it's
the real builtin range function, in which case it can emit/execute
machine code which is something like the C for loop:

    for (i=start; i<stop; i+=step) {
        do something interesting with i
    }

or not, in which case it has to call whatever range is, then respond
with its list of (arbtrary) Python objects.

Syntactic sugar would lock down the standard behavior.

Skip


More information about the Python-ideas mailing list