with_gil.pyx 10.7 KB
Newer Older
1
"""
2
Test the 'with gil:' statement.
3 4
"""

5 6 7
cimport cython

#from libc.stdio cimport printf, puts
8
from cpython cimport PyObject, Py_INCREF
9 10 11 12

import sys


13 14 15 16 17 18 19 20 21 22 23 24
def redirect_stderr(func, *args, **kwargs):
    """
    Helper function that redirects stderr to stdout for doctest.
    """
    stderr, sys.stderr = sys.stderr, sys.stdout
    func(*args, **kwargs)
    sys.stderr = stderr

cdef void puts(char *string) with gil:
    """
    We need this for doctest, used from nogil sections.
    """
25
    print string.decode('ascii')
26

27 28 29 30 31 32 33 34 35
class ExceptionWithMsg(Exception):
    """
    In python2.4 Exception is formatted as <exceptions.Exception
    instance at 0x1b8f948> when swallowed.
    """

    def __repr__(self):
        return "ExceptionWithMsg(%r)" % self.args

36 37 38 39

# Start with some normal Python functions

def test_simple():
40
    """
41
    >>> test_simple()
42 43 44 45 46 47
    ['spam', 'ham']
    """
    with nogil:
        with gil:
            print ['spam', 'ham']

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
def test_nested_gil_blocks():
    """
    >>> test_nested_gil_blocks()
    entered outer nogil section
    entered outer gil section
    entered inner nogil section
    entered inner gil section
    leaving inner gil section
    leaving inner nogil section
    leaving outer gil section
    leaving outer nogil section
    """

    with nogil:
        puts("entered outer nogil section")

        with gil:
            print 'entered outer gil section'

            with nogil:
                puts("entered inner nogil section")
                with gil:
                    print 'entered inner gil section'
                    print 'leaving inner gil section'
                puts("leaving inner nogil section")

            print "leaving outer gil section"
        puts("leaving outer nogil section")

def test_propagate_exception():
    """
    >>> test_propagate_exception()
    Traceback (most recent call last):
        ...
    Exception: This exception propagates!
    """
    # Note, doctest doesn't support both output and exceptions
    with nogil:
        with gil:
            raise Exception("This exception propagates!")

def test_catch_exception():
    """
    >>> test_catch_exception()
    This is executed
    Exception value
    This is also executed
    """
    try:
        with nogil:
            with gil:
                print "This is executed"
                raise Exception("Exception value")
                print "This is not executed"
            puts("This is also not executed")
    except Exception, e:
        print e
    print "This is also executed"

def test_try_finally_and_outer_except():
    """
    >>> test_try_finally_and_outer_except()
    First finally clause
Mark Florisson's avatar
Mark Florisson committed
111
    Second finally clause
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    Caught: Some Exception
    End of function
    """
    try:

        with nogil:
            with gil:
                try:
                    with nogil:
                        with gil:
                            try:
                                raise Exception("Some Exception")
                            finally:
                                puts("First finally clause")
                finally:
Mark Florisson's avatar
Mark Florisson committed
127
                    puts("Second finally clause")
128 129 130 131 132 133 134
            puts("This is not executed")

    except Exception, e:
        print "Caught:", e

    print "End of function"

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
def test_restore_exception():
    """
    >>> test_restore_exception()
    Traceback (most recent call last):
        ...
    Exception: Override the raised exception
    """
    with nogil:
        with gil:
            try:
                with nogil:
                    with gil:
                        raise Exception("Override this please")
            finally:
                raise Exception("Override the raised exception")

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
### DISABLED: this cannot work with flow control analysis
##
## def test_declared_variables():
##     """
##     >>> test_declared_variables()
##     None
##     None
##     ['s', 'p', 'a', 'm']
##     ['s', 'p', 'a', 'm']
##     """
##     cdef object somevar
##
##     print somevar
##
##     with nogil:
##         with gil:
##             print somevar
##             somevar = list("spam")
##             print somevar
##
##     print somevar

### DISABLED: this cannot work with flow control analysis
##
## def test_undeclared_variables():
##     """
##     >>> test_undeclared_variables()
##     None
##     None
##     ['s', 'p', 'a', 'm']
##     ['s', 'p', 'a', 'm']
##     """
##     print somevar
##     with nogil:
##         with gil:
##             print somevar
##             somevar = list("spam")
##             print somevar
##
##     print somevar
191 192 193 194 195 196 197 198 199 200 201 202 203 204

def test_loops_and_boxing():
    """
    >>> test_loops_and_boxing()
    spamham
    h
    a
    m
    done looping
    """
    cdef char c, *string = "spamham"

    with nogil:
        with gil:
205
            print string.decode('ascii')
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            for c in string[4:]:
                print "%c" % c
            else:
                print "done looping"

cdef class SomeExtClass(object):
    cdef int some_attribute

@cython.infer_types(True)
def test_infer_types():
    """
    >>> test_infer_types()
    10
    """
    with nogil:
        with gil:
            obj = SomeExtClass()
            obj.some_attribute = 10

    print obj.some_attribute

Mark Florisson's avatar
Mark Florisson committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
def test_closure():
    """
    >>> test_closure()
    Traceback (most recent call last):
        ...
    Exception: {'twinkle': 'little star'}
    """
    a = dict(twinkle='little star')

    def inner_function():
        with nogil:
            with gil:
                raise Exception(a)

    with nogil:
        with gil:
            inner_function()

    raise Exception("This should not be raised!")

247 248 249 250
cpdef test_cpdef():
    """
    >>> test_cpdef()
    Seems to work!
Mark Florisson's avatar
Mark Florisson committed
251
    Or does it?
252 253 254
    """
    with nogil:
        with gil:
255
            print "Seems to work!"
Mark Florisson's avatar
Mark Florisson committed
256
        puts("Or does it?")
257

258

259
# Now test some cdef functions with different return types
260

261
cdef void void_nogil_ignore_exception() nogil:
262
    with gil:
263
        raise ExceptionWithMsg("This is swallowed")
264

265
    puts("unreachable")
266 267 268
    with gil:
        print "unreachable"

Mark Florisson's avatar
Mark Florisson committed
269 270 271 272 273 274
cdef void void_nogil_nested_gil() nogil:
    with gil:
        with nogil:
            with gil:
                print 'Inner gil section'
            puts("nogil section")
275
        raise ExceptionWithMsg("Swallow this")
Mark Florisson's avatar
Mark Florisson committed
276 277 278
    puts("Don't print this")

def test_nogil_void_funcs_with_gil():
279
    """
Mark Florisson's avatar
Mark Florisson committed
280
    >>> redirect_stderr(test_nogil_void_funcs_with_gil)
281
    Exception with_gil.ExceptionWithMsg: ExceptionWithMsg('This is swallowed') in 'with_gil.void_nogil_ignore_exception' ignored
Mark Florisson's avatar
Mark Florisson committed
282 283
    Inner gil section
    nogil section
284
    Exception with_gil.ExceptionWithMsg: ExceptionWithMsg('Swallow this') in 'with_gil.void_nogil_nested_gil' ignored
285
    """
286
    void_nogil_ignore_exception()
Mark Florisson's avatar
Mark Florisson committed
287 288 289 290 291
    void_nogil_nested_gil()

def test_nogil_void_funcs_with_nogil():
    """
    >>> redirect_stderr(test_nogil_void_funcs_with_nogil)
292
    Exception with_gil.ExceptionWithMsg: ExceptionWithMsg('This is swallowed') in 'with_gil.void_nogil_ignore_exception' ignored
Mark Florisson's avatar
Mark Florisson committed
293 294
    Inner gil section
    nogil section
295
    Exception with_gil.ExceptionWithMsg: ExceptionWithMsg('Swallow this') in 'with_gil.void_nogil_nested_gil' ignored
Mark Florisson's avatar
Mark Florisson committed
296
    """
297 298
    with nogil:
        void_nogil_ignore_exception()
Mark Florisson's avatar
Mark Florisson committed
299
        void_nogil_nested_gil()
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

cdef PyObject *nogil_propagate_exception() nogil except NULL:
    with nogil:
        with gil:
            raise Exception("This exception propagates!")
    return <PyObject *> 1

def test_nogil_propagate_exception():
    """
    >>> test_nogil_propagate_exception()
    Traceback (most recent call last):
        ...
    Exception: This exception propagates!
    """
    nogil_propagate_exception()

317 318 319 320 321 322 323 324 325 326 327 328 329 330

cdef with_gil_raise() with gil:
    raise Exception("This exception propagates!")

def test_release_gil_call_gil_func():
    """
    >>> test_release_gil_call_gil_func()
    Traceback (most recent call last):
        ...
    Exception: This exception propagates!
    """
    with nogil:
        with gil:
            with_gil_raise()
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402


# Test try/finally in nogil blocks

def test_try_finally_in_nogil():
    """
    >>> test_try_finally_in_nogil()
    Traceback (most recent call last):
        ...
    Exception: Override exception!
    """
    with nogil:
        try:
            with gil:
                raise Exception("This will be overridden")
        finally:
            with gil:
                raise Exception("Override exception!")

            with gil:
                raise Exception("This code should not be executed!")

def test_nogil_try_finally_no_exception():
    """
    >>> test_nogil_try_finally_no_exception()
    first nogil try
    nogil try gil
    second nogil try
    nogil finally
    ------
    First with gil block
    Second with gil block
    finally block
    """
    with nogil:
        try:
            puts("first nogil try")
            with gil:
                print "nogil try gil"
            puts("second nogil try")
        finally:
            puts("nogil finally")

    print '------'

    with nogil:
        try:
            with gil:
                print "First with gil block"

            with gil:
                print "Second with gil block"
        finally:
            puts("finally block")

def test_nogil_try_finally_propagate_exception():
    """
    >>> test_nogil_try_finally_propagate_exception()
    Execute finally clause
    Propagate this!
    """
    try:
        with nogil:
            try:
                with gil:
                    raise Exception("Propagate this!")
                with gil:
                    raise Exception("Don't reach this section!")
            finally:
                puts("Execute finally clause")
    except Exception, e:
        print e
403 404 405 406

def test_nogil_try_finally_return_in_with_gil(x):
    """
    >>> test_nogil_try_finally_return_in_with_gil(10)
407
    print me
408 409 410 411 412 413 414 415
    10
    """
    with nogil:
        try:
            with gil:
                raise Exception("Swallow me!")
        finally:
            with gil:
416
                print "print me"
417 418
                return x

419
    print "I am not executed"
420 421 422 423 424 425 426

cdef void nogil_try_finally_return() nogil:
    try:
        with gil:
            raise Exception("I am swallowed in nogil code... right?")
    finally:
        with gil:
427
            print "print me first"
428 429 430 431

        return

    with gil:
432
        print "I am not executed"
433 434 435 436

def test_nogil_try_finally_return():
    """
    >>> test_nogil_try_finally_return()
437
    print me first
438 439 440
    """
    with nogil:
        nogil_try_finally_return()
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

cdef int error_func() except -1 with gil:
    raise Exception("propagate this")

def test_nogil_try_finally_error_label():
    """
    >>> test_nogil_try_finally_error_label()
    print me first
    propagate this
    """
    try:
        with nogil:
            try:
                error_func()
            finally:
                with gil: print "print me first"
    except Exception, e:
        print e.args[0]