[Python-Dev] Rewrite @contextlib.contextmanager in C (original) (raw)

Yury Selivanov yselivanov.ml at gmail.com
Mon Aug 8 16:38:51 EDT 2016


On 2016-08-08 4:18 PM, Guido van Rossum wrote:

I think Nick would be interested in understanding why this is the case. What does the decorator do that could be so expensive?

From the looks of it it doesn't do anything special. Although with @contextlib.contextmanager we have to instantiate a generator (the decorated one) and advance it in enter. So it's an extra object instantiation + extra code in enter and exit. Anyways, Nick knows much more about that code.

Giampaolo, before experimenting with a C implementation, I suggest you to try to compile contextlib.py with Cython. I'll be surprised if you can make it more than 30-40% faster. And you won't get much faster than Cython when you code contextmanager in C by hand.

Also, we don't have slots for enter and exit, so there is no way to avoid the attribute lookup.

Yury



More information about the Python-Dev mailing list