C API: Making a context manager

Chris Kaynor ckaynor at zindagigames.com
Mon Oct 31 14:34:31 EDT 2011


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.

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()

For this, my first question is: is there any built-in method to make
this type of method in the C API? If not, is there a slot on the type
object I am missing for __enter__ and __exit__, or should just be
defined using the PyMethodDef struct on the class (presumably named
the same as the Python functions)?

Chris



More information about the Python-list mailing list