C API: Making a context manager



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
.



Relevant Pages

  • Re: Accessors in Python (getters and setters)
    ... used it in 27000 lines of Python code (which certainly took some time to ... Naming attributes and naming methods are entirely different ... operator only to callables, but this doesn't make such a difference ... But it's *your* responsability to choose good names for the API.> ...
    (comp.lang.python)
  • Re: zlib interface semi-broken
    ... implement one-shot de/compression of strings. ... functions that do one-shot compression and decompression. ... That file interface could form a third API, ... conform to what python expects of files. ...
    (comp.lang.python)
  • Re: Accessors in Python (getters and setters)
    ... used it in 27000 lines of Python code (which certainly took some time to ... develops might misinterpret exactly what "tmp" does. ... Failing to understand a language semantics ... But it's *your* responsability to choose good names for the API.> ...
    (comp.lang.python)
  • Re: Whats so funny? WAS Re: rotor replacement
    ... I don't disagree about the API. ... AES module (or rather, a generic block cipher module with AES and DES) ... if I want ECC in a Python ...
    (comp.lang.python)
  • Re: OpenGL
    ... It was originally written in pure Python C-extension code, then Tarn rewrote it using SWIG a few years ago. ... OpenGL-ctypes is in the PyOpenGL CVS repository, it's a ctypes re-re-implementation of the same Python API to OpenGL. ... Basically any array type can be registered with handlers that let you tell the system how to do basic operations; get an array's size, shape, data-type, convert to a given data-format, build an "empty" array of a given size, that kind of thing. ...
    (comp.lang.python)