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

(Sorry about the formatting - I'm a former student of Annie's, who just joined the list.) Jim Jewett wrote:
Even in this thread, there have been multiple posts that would shown bugs when the witness itself had a boolean evaluation of False. What if any and all started to return a Witness object that evaluated to True/False, but made the value available? I could see an object like this being useful in other code as well. class Witness(object): def __bool__(self): return self.truth def __init__(self, truth, value): self.truth=truth self.value=value Of course, it might be nicer to inherit from type(True), and it still doesn't quite solve the laziness problem with for, or the assign-in-the-right-place problem with while.
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 Another use of this could be for database queries that return 0 or 1 results: if db.query(page_name=page_name) as page: render_template(page) else: error404() This is a common pattern that often involves either exception handling or a sentinel value like None.

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: render_template(page) break else: error404() -Alexander
participants (2)
-
Alexander Heger
-
Tom Rothamel