seeking deeper (language theory) reason behind Python design choice

Chris Angelico rosuav at gmail.com
Fri May 11 11:38:37 EDT 2018


On Sat, May 12, 2018 at 1:03 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Fri, May 11, 2018 at 7:40 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> So, yes, your function's name is outright lying. But there's nothing
>> about it that is *pretending* to be a normal function. It IS a normal
>> function.
>
> The detail of whether it's a generator function affects the function's
> execution and may be relevant to the caller. Here are two hypothetical
> functions. They do some processing with side-effects over a bunch of
> items and return the processed items. However, one is a generator
> function and the other just returns a list.
>
> def process_items(items):
>     ...
>
> def handle_items(items):
>     ...
>
> Now, we can agree that these ought to be better documented, but say I
> want to call one of these for the side effects and ignore the return
> value. Just from reading the first line of the function, do I need to
> iterate over the result, or not?

This is no different from anything else you might need to know about
the functions. It might be essential to know that "handle_items"
actually doesn't return anything at all, and signals success or
failure by what exception it raises. Or that "process_items", due to
internal structure and implementation, absolutely must be called from
the main thread, otherwise you risk OS-level signals corrupting your
data. The solution is simple: read the docstring.

> Scenario 2. I have two "while True" loops. One is potentially infinite
> and the other is not.
>
> while True:
>     ...
>
> while True:
>     ...
>
> Obviously, it's important to know whether a loop might be infinite
> before I run the code that includes it. Just from reading the first
> line of the loop, how do I know? You can argue that they should use
> strings instead to describe what they do, which would help, although I
> think that's potentially confusing.
>
> I don't see these two situations as being fundamentally different. Do you?

Not hugely, no. But it's worth noting that we have the option to
annotate a function's return value. So if you need structured
information about what this function or that function returns, you can
provide that. It's not easy to make program-readable information about
a 'while' loop (since it's not a first-class object), but you can
still have structured information about whether the loop is infinite
or not, by putting it into the loop header.

But I still think you're overblowing the case when you claim that a
generator function isn't a function. That'd be on par with claiming
that a while loop isn't a loop.

ChrisA



More information about the Python-list mailing list