C API: Making a context manager

C

Chris Kaynor

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top