[Python-ideas] Fwd: quantifications, and tuple patterns

Alexander Heger python at 2sn.net
Tue Jan 17 05:00:52 CET 2012

Dear Tom,

> I'm wondering if would make sense to add an "as" clause to the while and if
> statements, similar to the as clause in the with statement. It would
> essentially retrieve the value field from the witness object described
> above.
> This would let one write the main loop in a topological sort (a classic
> workset algorithm) as:
>      while any(v for v in vertices if v.incoming_count == 0) as v1:
>          result.append(v)
>          for v2 in v1.outgoing:
>              v2.incoming_count -= 1

I had the same thought going through the thread, but I think the problem 
here would be that any is a function that returns a Boolean value.  You 
could add a key parameter to return something else, say a tuple of a 
truth value and a sample ( any( ..., sample = True) ) but that could 
break because

1) "any" could be another function in the context,

2) while would need to deal with special return values in this case

A suggestion to replace the "while any" case is

sample <generator expression> as x:
    # do something with x

  ("sample" may not be the best keyword choice) From the discussion so 
far I do not see how to easily avoid having a new keyword

specifically, your example would become

sample v for v in vertices if v.incoming_count == 0 as v1:
     # do things with v1

In case you only want one sample, you could add the break statement

sample db.query(page_name=page_name) as page:


More information about the Python-ideas mailing list