An exception can be raised at the current yield with foo.raise(). -> with foo.throw().
In sorted(self.letters.items(), key=lambda kv: kv[1]) the lambda can be replaced with operator.itemgetter(1), it's one of my favorite small things that are in the standard library :D
I was wondering if there was a way to simplify the coroutine code, using a context manager. The __enter__ could call send(None) and the __exit__ could call close().
With a simple generator is easy to do something similar:
Ooh! Thanks for catching that typo! That would have been confusing.
As to the lambda or itemgetter(), I'd actually gone back and forth between the two in writing that example. I think using the lambda there is my own personal preference more than anything.
That is certainly a clever combination of a context and a coroutine, by the way. (Naturally, I didn't discuss contexts in this article, as I haven't discussed them yet in the series.)
Thanks for the feedback.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Great article Jason!
Just a couple of details:
An exception can be raised at the current yield with foo.raise().
->with foo.throw().
In
sorted(self.letters.items(), key=lambda kv: kv[1])
the lambda can be replaced with operator.itemgetter(1), it's one of my favorite small things that are in the standard library :DI was wondering if there was a way to simplify the coroutine code, using a context manager. The
__enter__
could callsend(None)
and the__exit__
could callclose()
.With a simple generator is easy to do something similar:
But the same doesn't work for a coroutine...
As a first I came up with this:
I came up with something like this then:
but I'm not sure it's improving much :D
Ooh! Thanks for catching that typo! That would have been confusing.
As to the lambda or
itemgetter()
, I'd actually gone back and forth between the two in writing that example. I think using the lambda there is my own personal preference more than anything.That is certainly a clever combination of a context and a coroutine, by the way. (Naturally, I didn't discuss contexts in this article, as I haven't discussed them yet in the series.)
Thanks for the feedback.