seeking deeper (language theory) reason behind Python design choice

Ian Kelly ian.g.kelly at gmail.com
Fri May 11 03:02:10 EDT 2018


On Fri, May 11, 2018 at 12:03 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Thu, 10 May 2018 20:38:39 -0600, Ian Kelly wrote:
>
>> Would you also contend that generator functions are wrong because they
>> pretend to be normal functions?
>
> You're going to need to be more specific. In what way are they not normal
> functions? You call them like normal functions, providing arguments like
> normal functions, and receiving a result just like normal functions.

The way that they execute is not like a normal function. If you call
one, having read the code but having failed to notice the 'yield', you
will be confused by the result.

Likewise, if you run a while True loop (or *any* loop, really), having
read the code but failed to notice the 'break', you will be confused
by the result.

The point being that you cannot necessarily infer what a while loop
will do just by reading the loop condition, any more than you can know
what a function call will return if all you've read are the name and
the signature.

> If you call a function like iter(), you also get back an iterator, just
> as you do when you call a generator. Is iter() not a normal function?

Presumably somebody experienced with Python will already know what
iter does without needing to read the code.

>> def totally_not_a_generator(n):
>>     while True:
>>         if n % 2 == 0:
>>             n //= 2
>>         else:
>>             n = n * 3 + 1
>>         stealthily = n
>>         yield stealthily
>>         if n == 1:
>>             return n
>
> I must admit, I'm a little perplexed. In what way is this totally not a
> generator? (To be precise, a generator function.) The inspect module
> thinks it is (and so do I):

The example was tongue-in-cheek. As suggested by the comment in the
part that you cut out where I called it, the code is lying.



More information about the Python-list mailing list