[Python-ideas] Does jargon make learning more difficult?
Rhodri James
rhodri at kynesim.co.uk
Wed Aug 22 13:56:51 EDT 2018
On 22/08/18 14:38, Jonathan Fine wrote:
> 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.
If by "help" you mean "make even more confused", then yes. Surprise is
a given with generators, as I said.
>
>>>> 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.
Ew.
I'd prefer this way of doing it:
def my_very_long_function_with_one_yield_point(...):
# This is a generator
--
Rhodri James *-* Kynesim Ltd
More information about the Python-ideas
mailing list