C API: Making a context manager

Brian Curtin brian.curtin at gmail.com
Mon Oct 31 15:15:37 EDT 2011


On Mon, Oct 31, 2011 at 13:34, Chris Kaynor <ckaynor at zindagigames.com> wrote:
> 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)?

You'd just add "__enter__" and "__exit__" in the PyMethodDef. If you
have the CPython source, we do it in there in a few places. Off the
top of my head, PC\winreg.c contains at least one class that works as
a context manager (PyHKEY), although there are a few others scattered
around the source.



More information about the Python-list mailing list