[Python-Dev] Rewrite @contextlib.contextmanager in C
Serhiy Storchaka
storchaka at gmail.com
Tue Aug 9 15:58:14 EDT 2016
On 09.08.16 00:59, Chris Angelico wrote:
> class TooSimpleContextManager:
> """Now this time you've gone too far."""
> def __init__(self, func):
> self.func = func
> def __call__(self):
> self.gen = self.func()
> return self
> def __enter__(self):
> next(self.gen)
> def __exit__(self, type, value, traceback):
> try: next(self.gen)
> except StopIteration: pass
[...]
> My numbers are:
>
> 0.320 secs
> 1.354 secs
> slowdown: -4.23x
> 0.899 secs
> slowdown: -2.81x
> 0.831 secs
> slowdown: -2.60x
> 0.868 secs
> slowdown: -2.71x
I have got a slowdown 1.74x with TooSimpleContextManager with following
implementation of __enter__ and __exit__:
def __enter__(self):
for res in self.gen:
return res
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
for _ in self.gen:
raise RuntimeError("generator didn't stop")
More information about the Python-Dev
mailing list