Using contextlib with cython cdef classes

16 views
Skip to first unread message

Anish Narayanan

unread,
Jun 25, 2017, 2:26:19 AM6/25/17
to cython-users
Hello everyone,

I have been running into some trouble using `contextlib` with cython `cdef` classes. I reported the issue here, but I unfortunately cannot reopen it. Here is the code for my cython module, `vbo.pyx`:

# cython: binding=True
import contextlib

cdef class Vbo:

    def __init__(self):
        pass
    
    @contextlib.contextmanager
    def bind(self):
        self.do_something()
        try:
            yield
        finally:
            print("Finally")

    def do_something(self):
        print("something")

The solution suggested on the issue page, using that `binding=True` compiler directive, only leads to a different error for me, which appears only on calling `with my_vbo_name.bind():`:

Traceback (most recent call last):
  File "main.py", line 28, in <module>
    with v.bind():
  File "C:\Python27\lib\contextlib.py", line 17, in __enter__
    return self.gen.next()
AttributeError: 'GeneratorContextManager' object has no attribute 'next'

This code does work, without the directive, if I remove the `cdef` part before my class, but I need to type some variables with `cdef` in my actual `vbo.pyx` so this is not particularly useful. Any help would be appreciated. 

Thanks,
Anish
Reply all
Reply to author
Forward
0 new messages