[Python-ideas] Contraction for "for x in range()"

Nick Timkovich prometheus235 at gmail.com
Tue Feb 14 18:41:34 EST 2017


Make some shim object that you can index into to get that functionality,
could even call it Z (for the set of all integers). Short, and requires no
new syntax.

class IndexableRange:
    def __getitem__(self, item):
        if isinstance(item, slice):
            start = item.start if item.start is not None else 0
            step = item.step if item.step is not None else 1
            if item.stop is None:
                return itertools.count(start, step)
            else:
                return range(start, item.stop, step)
        else:
            return item

Z = IndexableRange()

for y in Z[0:10:2]:
    print(y)

On Tue, Feb 14, 2017 at 5:22 PM, Mikhail V <mikhailwas at gmail.com> wrote:

>
> On 14 February 2017 at 22:41, MRAB <python at mrabarnett.plus.com> wrote:
>
>> On 2017-02-14 21:09, Zachary Ware wrote:
>>
>>> On Tue, Feb 14, 2017 at 3:06 PM, Mikhail V <mikhailwas at gmail.com> wrote:
>>>
>>>> I have a small syntax idea.
>>>> In short, contraction of
>>>>
>>>> for x in range(a,b,c) :
>>>>
>>>> to
>>>>
>>>> for x in a,b,c :
>>>>
>>>> I really think there is something cute in it.
>>>> So like a shortcut for range() which works only in for-in statement.
>>>> So from syntactical POV, do you find it nice syntax?
>>>> Visually it seems to me less bulky than range().
>>>>
>>>> Example:
>>>>
>>>> for x in 0,5 :
>>>>     print (x)
>>>>     for y in 0,10,2 :
>>>>         print (y)
>>>>         for z in 0, y+8 :
>>>>             print (z)
>>>>
>>>
>>> This is already valid and useful syntax, and thus a non-starter.
>>>
>>>
>>>
>>> The closest you could get without breaking existing code is [a:b:c]:
>>
>> for x in [0:5]:
>>     print(x)
>>     for y in [0:10:2]:
>>         print(y)
>>         for z in [0:y+8]:
>>             print(z)
>>
>> What's more, that could be valid outside the 'for' loop too.
>>
>>
> This looks really good, at first glance I would even expect this will
> work,
> comes so common from lists and numpy index ranges.
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170214/3309fbdd/attachment-0001.html>


More information about the Python-ideas mailing list