while expression feature proposal

Tim Chase python.list at tim.thechases.com
Sat Oct 27 15:15:32 EDT 2012


On 10/26/12 19:18, Steven D'Aprano wrote:
> def iterate_until_none_or_false(func, *args, **kwargs):
>     while True:
>         x = func(*args, **kwargs)
>         # Halt if x is None or False, but not other falsey values.
>         if x is None or x is False:
>             return
>         yield x
> 
> for x in iterate_until_none_or_false(
>         some_function, 1, 2, "c", spam="yummy"):
>     process(x)

I was initially a pretty strong advocate of the proposed "as"
syntax.  However, the more I've thought about it, the more I keep
coming back to how I've solved the problem in the past which is
mostly what Steven suggests here.  There are so many edge-cases and
warts in the "as" syntax; most of which disappear with this
generator+forloop:

- yielding/unpacking multiple results  each time: the "as" syntax
would get really ugly.  Do you test the whole result, or an element
of the result?

- knowing the stopping condition varies: is it when something is
False-ish (an empty string/tuple/list, False, None, etc)?  When it
"is None"?  When it is exactly "False"?

- the whole "x = (foo(bar) as result) if result else None" (or
should that be "x = result if (foo(bar) as result) else None"?)
style/discussion just really looks ugly to me.  Usually I find
Python code quite beautiful and this syntax doesn't resonate as
"beautiful".

To despite my previous excitement, I'm now neutral at best on a
limited "while TERM as VAR:" syntax.

I know this "being persuaded by rational arguments and changing
one's mind" thing is rare on the Intarwebs, so I hope I haven't
upset the natural balance of things too greatly. :-)

-tkc








More information about the Python-list mailing list