[Python-ideas] Does jargon make learning more difficult?

Jonathan Fine jfine2358 at gmail.com
Wed Aug 22 09:38:07 EDT 2018


Hi Rhodri

You wrote:

>This, by the way, is why think using the same syntax for function definition and generator definition was a mistake. It's only when I reach a "yield" statement that I realise my expectations for this code are wrong.

Here's something that might help, and surprise, you. This has been
present since Python 2.5.

>>> def fn():
...     if None:
...         yield
...
>>> list(fn()) # Fails, unless fn is a generator function.
[]

I think what's happening is this. Even though the None-guarded yield
has been optimised away, it leaves a residue. Namely, that there's a
yield in the function. Hence fn() is an iterator.

Having explained the surprise, here's how it can help you. Suppose you
have a long function body, with a single yield at the bottom. If you
write like this:

    def my_very_long_function_with_one_yield_point(...):
        if None: yield # This is a generator function.

then the next programmer can know immediately that it's a generator function.

-- 
Jonathan


More information about the Python-ideas mailing list