Promoting Python

Marko Rauhamaa marko at pacujo.net
Wed Apr 6 15:22:04 EDT 2016


Ian Kelly <ian.g.kelly at gmail.com>:

> On Wed, Apr 6, 2016 at 8:14 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
>> Now, if Python had an unlimited range() iterator/iterable, you could use
>> a "for" statement to emulate "while".
>
> You can already do this.
>
>>>> class While:
> ...     def __init__(self, predicate):
> ...         self._predicate = predicate
> ...         self._exited = False
> ...     def __iter__(self):
> ...         return self
> ...     def __next__(self):
> ...         if self._exited or not self._predicate():
> ...             self._exited = True
> ...             raise StopIteration
> ...
>>>> i = 0
>>>> for _ in While(lambda: i < 10):
> ...     print(i)
> ...     i += 1
> ...
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9

Impressive!

>> As it stands, Python without "while" could only compute
>> primitive-recursive functions. However, you only need "while" a
>> maximum of one time in your whole program to perform an arbitrary
>> computation.
>
> So this is wrong.

I stand corrected.

However, BartC's No-Buzzword Python doesn't have classes... If he
allowed for types.SimpleNamespace, we could have:

========================================================================
import types

def While(predicate):
    def __iter__():
        return thingy
    def __next__():
        if thingy._exited or not predicate():
            thingy._exited = True
            raise StopIteration
    thingy = types.SimpleNamespace(
        _exited=False, __iter__=__iter__, __next__=__next__)
    return thingy
========================================================================

However, that results in:

    TypeError: 'types.SimpleNamespace' object is not iterable

Where's my bug? Or is CPython buggy? Or is it the documentation:

    The iterator objects themselves are required to support the
    following two methods, which together form the iterator protocol:

    iterator.__iter__()

    [...]

    iterator.__next__()

    <URL: https://docs.python.org/3/library/stdtypes.html#typeiter>

Why is a SimpleNamespace object not an iterator even though it provides
__iter__ and __next__?


Marko



More information about the Python-list mailing list