In an exception handler for a CSP style process, I need to read and discard the entire contents of a channel in order to allow other processes that are blocking to send to it to complete. The interface presents a generator for receiving, is there a faster way to consume and discard the entire contents of a generator than the following?
for _ in chan:
pass
I've started using a deque that I can reuse if need be:
Then I can consume generator expressions using:
You might try:
But honestly I don't think you're going to do much better than the plain loop. "channel" suggests I/O which is going to be the bottleneck anyway.
There is a way that is slightly faster:
Your code makes the intention much clearer, though, so you should measure if there is a discernible difference. I'd almost always prefer your code.
(I'd never use
_
as a variable name, though. It tends to confuse people, clashes with_
in the interactive shell and with the commongettext
alias.)Edit: Here are some simple timings: