C API: Making a context manager
Stefan Behnel
stefan_ml at behnel.de
Tue Nov 1 11:57:02 EDT 2011
Chris Kaynor, 31.10.2011 19:34:
> I am currently rewritting a class using the Python C API to improve
> performance of it, however I have not been able to find any
> documentation about how to make a context manager using the C API.
You should take a look at Cython. It makes these things *so* much easier.
> The code I am working to produce is the following (its a method of a class):
>
> @contextlib.contextmanager
> def connected(self, *args, **kwargs):
> connection = self.connect(*args, **kwargs)
> try:
> yield
> finally:
> connection.disconnect()
You can use the above in Cython code unmodified, and it's likely going to
be good enough (depending on what kind of connection we are talking about
here).
In case that's also performance critical, however, it's likely faster to
spell it out as a class, i.e.
...
def connected(self, *args, **kwargs):
return ConnectionManager(self, args, kwargs)
cdef class ConnectionManager:
cdef object args, kwargs, connection, connect
def __init__(self, connector, args, kwargs):
self.args, self.kwargs = args, kwargs
self.connect = connector.connect
def __enter__(self):
self.connection = self.connect(*self.args, **self.kwargs)
def __exit__(self, *exc):
self.connection.disconnect()
return True # or False? I always forget which means what
Not that much longer either.
Stefan
More information about the Python-list
mailing list