Commit a2bbb8f0 authored by Robert Bradshaw's avatar Robert Bradshaw

Move some tests into function docstrings.

parent cad68bb9
...@@ -433,6 +433,7 @@ is_private_field = re.compile('^_[^_]').match ...@@ -433,6 +433,7 @@ is_private_field = re.compile('^_[^_]').match
class _FakeClass(object): class _FakeClass(object):
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.shortDescription = lambda x: kwargs.get('module_name')
self.__dict__.update(kwargs) self.__dict__.update(kwargs)
try: # Py2.7+ and Py3.2+ try: # Py2.7+ and Py3.2+
......
...@@ -5,27 +5,33 @@ __doc__ = u""" ...@@ -5,27 +5,33 @@ __doc__ = u"""
>>> x >>> x
46 46
>>> add_pyrange(10)
46
>>> add_py(10)
46
>>> add_c(10)
46
""" """
def add_pyrange(max): def add_pyrange(max):
"""
>>> add_pyrange(10)
46
"""
x = 1 x = 1
for i in range(max): for i in range(max):
x = x + i x = x + i
return x return x
def add_py(max): def add_py(max):
"""
>>> add_py(10)
46
"""
x = 1 x = 1
for i from 0 <= i < max: for i from 0 <= i < max:
x = x + i x = x + i
return x return x
def add_c(max): def add_c(max):
"""
>>> add_c(10)
46
"""
cdef int x,i cdef int x,i
x = 1 x = 1
for i from 0 <= i < max: for i from 0 <= i < max:
......
__doc__ = u""" def f():
"""
>>> f() >>> f()
(30, 22) (30, 22)
""" """
def f():
cdef int int1, int2, int3 cdef int int1, int2, int3
cdef char *ptr1, *ptr2 = "test", *ptr3 = "toast" cdef char *ptr1, *ptr2 = "test", *ptr3 = "toast"
int2 = 10 int2 = 10
......
__doc__ = u""" def f(int a):
"""
>>> f(5) >>> f(5)
5 5
""" """
def f(int a):
cdef int i,j cdef int i,j
cdef int *p cdef int *p
i = a i = a
......
__doc__ = u"""
>>> func1(None)
>>> func1(*[None])
>>> func1(arg=None)
Traceback (most recent call last):
...
TypeError: func1() takes no keyword arguments
>>> func2(None)
>>> func2(*[None])
>>> func2(arg=None)
Traceback (most recent call last):
...
TypeError: func2() takes no keyword arguments
>>> func3(None)
>>> func3(*[None])
>>> func3(arg=None)
>>> A().meth1(None)
>>> A().meth1(*[None])
>>> A().meth1(arg=None)
Traceback (most recent call last):
...
TypeError: meth1() takes no keyword arguments
>>> A().meth2(None)
>>> A().meth2(*[None])
>>> A().meth2(arg=None)
Traceback (most recent call last):
...
TypeError: meth2() takes no keyword arguments
>>> A().meth3(None)
>>> A().meth3(*[None])
>>> A().meth3(arg=None)
"""
cimport cython cimport cython
def func1(arg): def func1(arg):
"""
>>> func1(None)
>>> func1(*[None])
>>> func1(arg=None)
Traceback (most recent call last):
...
TypeError: func1() takes no keyword arguments
"""
pass pass
@cython.always_allow_keywords(False) @cython.always_allow_keywords(False)
def func2(arg): def func2(arg):
"""
>>> func2(None)
>>> func2(*[None])
>>> func2(arg=None)
Traceback (most recent call last):
...
TypeError: func2() takes no keyword arguments
"""
pass pass
@cython.always_allow_keywords(True) @cython.always_allow_keywords(True)
def func3(arg): def func3(arg):
"""
>>> func3(None)
>>> func3(*[None])
>>> func3(arg=None)
"""
pass pass
cdef class A: cdef class A:
"""
>>> A().meth1(None)
>>> A().meth1(*[None])
>>> A().meth1(arg=None)
Traceback (most recent call last):
...
TypeError: meth1() takes no keyword arguments
>>> A().meth2(None)
>>> A().meth2(*[None])
>>> A().meth2(arg=None)
Traceback (most recent call last):
...
TypeError: meth2() takes no keyword arguments
>>> A().meth3(None)
>>> A().meth3(*[None])
>>> A().meth3(arg=None)
"""
def meth1(self, arg): def meth1(self, arg):
pass pass
......
__doc__ = u""" a,b = 'a *','b *' # use non-interned strings
>>> a,b = 'a *','b *' # use non-interned strings
>>> and2_assign(2,3) == (2 and 3)
True
>>> and2_assign('a', 'b') == ('a' and 'b')
True
>>> and2_assign(a, b) == (a and b)
True
>>> and2(2,3) == (2 and 3)
True
>>> and2(0,2) == (0 and 2)
True
>>> and2('a', 'b') == ('a' and 'b')
True
>>> and2(a, b) == (a and b)
True
>>> and2('', 'b') == ('' and 'b')
True
>>> and2([], [1]) == ([] and [1])
True
>>> and2([], [a]) == ([] and [a])
True
>>> and3(0,1,2) == (0 and 1 and 2)
True
>>> and3([],(),[1]) == ([] and () and [1])
True
>>> and2_no_result(2,3)
>>> and2_no_result(0,2)
>>> and2_no_result('a','b')
>>> and2_no_result(a,b)
>>> a and b
'b *'
"""
def and2_assign(a,b): def and2_assign(a,b):
"""
>>> a,b = 'a *','b *' # use non-interned strings
>>> and2_assign(2,3) == (2 and 3)
True
>>> and2_assign('a', 'b') == ('a' and 'b')
True
>>> and2_assign(a, b) == (a and b)
True
"""
c = a and b c = a and b
return c return c
def and2(a,b): def and2(a,b):
"""
>>> and2(2,3) == (2 and 3)
True
>>> and2(0,2) == (0 and 2)
True
>>> and2('a', 'b') == ('a' and 'b')
True
>>> and2(a, b) == (a and b)
True
>>> and2('', 'b') == ('' and 'b')
True
>>> and2([], [1]) == ([] and [1])
True
>>> and2([], [a]) == ([] and [a])
True
"""
return a and b return a and b
def and3(a,b,c): def and3(a,b,c):
"""
>>> and3(0,1,2) == (0 and 1 and 2)
True
>>> and3([],(),[1]) == ([] and () and [1])
True
"""
d = a and b and c d = a and b and c
return d return d
def and2_no_result(a,b): def and2_no_result(a,b):
"""
>>> and2_no_result(2,3)
>>> and2_no_result(0,2)
>>> and2_no_result('a','b')
>>> and2_no_result(a,b)
>>> a and b
'b *'
"""
a and b a and b
__doc__ = u"""
>>> test_append([])
None
None
None
got error
[1, 2, (3, 4)]
>>> _ = test_append(A())
appending
1
appending
2
appending
(3, 4)
got error
>>> test_append(B())
None
None
None
None
[1, 2, (3, 4), 5, 6]
"""
class A: class A:
def append(self, x): def append(self, x):
print u"appending" print u"appending"
...@@ -32,6 +9,28 @@ class B(list): ...@@ -32,6 +9,28 @@ class B(list):
list.append(self, arg) list.append(self, arg)
def test_append(L): def test_append(L):
"""
>>> test_append([])
None
None
None
got error
[1, 2, (3, 4)]
>>> _ = test_append(A())
appending
1
appending
2
appending
(3, 4)
got error
>>> test_append(B())
None
None
None
None
[1, 2, (3, 4), 5, 6]
"""
print L.append(1) print L.append(1)
print L.append(2) print L.append(2)
print L.append((3,4)) print L.append((3,4))
...@@ -40,4 +39,3 @@ def test_append(L): ...@@ -40,4 +39,3 @@ def test_append(L):
except TypeError: except TypeError:
print u"got error" print u"got error"
return L return L
__doc__ = u"""
>>> f0()
(1, 2)
>>> g0()
(1, 2)
>>> f1()
[1, 2]
>>> g1()
[1, 2]
>>> f2()
{1: 2}
>>> g2()
{1: 2}
>>> f3() #doctest: +ELLIPSIS
<argdefault.Foo object at ...>
>>> g3() #doctest: +ELLIPSIS
<argdefault.Foo object at ...>
>>> f4() #doctest: +ELLIPSIS
<argdefault.Bar object at ...>
>>> g4() #doctest: +ELLIPSIS
<argdefault.Bar object at ...>
>>> f5() #doctest: +ELLIPSIS
<argdefault.Bla object at ...>
>>> g5() #doctest: +ELLIPSIS
<argdefault.Bla object at ...>
>>> f6()
7
>>> g6()
7
"""
GLB0 = (1, 2) GLB0 = (1, 2)
def f0(arg=GLB0): def f0(arg=GLB0):
"""
>>> f0()
(1, 2)
"""
return arg return arg
def g0(arg=(1, 2)): def g0(arg=(1, 2)):
"""
>>> g0()
(1, 2)
"""
return arg return arg
GLB1 = [1, 2] GLB1 = [1, 2]
def f1(arg=GLB1): def f1(arg=GLB1):
"""
>>> f1()
[1, 2]
"""
return arg return arg
def g1(arg=[1, 2]): def g1(arg=[1, 2]):
"""
>>> g1()
[1, 2]
"""
return arg return arg
cdef GLB2 = {1: 2} cdef GLB2 = {1: 2}
def f2(arg=GLB2): def f2(arg=GLB2):
"""
>>> f2()
{1: 2}
"""
return arg return arg
def g2(arg={1: 2}): def g2(arg={1: 2}):
"""
>>> g2()
{1: 2}
"""
return arg return arg
...@@ -60,8 +47,16 @@ class Foo(object): ...@@ -60,8 +47,16 @@ class Foo(object):
pass pass
cdef GLB3 = Foo() cdef GLB3 = Foo()
def f3(arg=GLB3): def f3(arg=GLB3):
"""
>>> f3() #doctest: +ELLIPSIS
<argdefault.Foo object at ...>
"""
return arg return arg
def g3(arg=Foo()): def g3(arg=Foo()):
"""
>>> g3() #doctest: +ELLIPSIS
<argdefault.Foo object at ...>
"""
return arg return arg
...@@ -69,8 +64,16 @@ cdef class Bar: ...@@ -69,8 +64,16 @@ cdef class Bar:
pass pass
cdef Bar GLB4 = Bar() cdef Bar GLB4 = Bar()
def f4(arg=GLB4): def f4(arg=GLB4):
"""
>>> f4() #doctest: +ELLIPSIS
<argdefault.Bar object at ...>
"""
return arg return arg
def g4(arg=Bar()): def g4(arg=Bar()):
"""
>>> g4() #doctest: +ELLIPSIS
<argdefault.Bar object at ...>
"""
return arg return arg
...@@ -78,13 +81,29 @@ cdef class Bla: ...@@ -78,13 +81,29 @@ cdef class Bla:
pass pass
cdef Bla GLB5 = Bla() cdef Bla GLB5 = Bla()
def f5(Bla arg=GLB5): def f5(Bla arg=GLB5):
"""
>>> f5() #doctest: +ELLIPSIS
<argdefault.Bla object at ...>
"""
return arg return arg
def g5(Bla arg=Bla()): def g5(Bla arg=Bla()):
"""
>>> g5() #doctest: +ELLIPSIS
<argdefault.Bla object at ...>
"""
return arg return arg
cdef int GLB6 = 7 cdef int GLB6 = 7
def f6(int arg=GLB6): def f6(int arg=GLB6):
"""
>>> f6()
7
"""
return arg return arg
def g6(int arg=7): def g6(int arg=7):
"""
>>> g6()
7
"""
return arg return arg
__doc__ = u"""
>>> test_literal_list_slice_all()
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start()
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_end()
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_end()
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_param(4)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_param(3)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_param(5)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_end_param(5)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_end_param(4)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_end_param(6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_end_param(2,7)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_end_param(3,7)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_start_end_param(1,7)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_end_param(2,6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_start_end_param(2,8)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_end_param(3,6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 3
>>> test_literal_list_slice_start_end_param(1,8)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 7
>>> test_ptr_literal_list_slice_all()
(1, 2, 3, 4, 5)
>>> test_ptr_literal_list_slice_start()
(1, 2, 3, 4, 5)
>>> test_ptr_literal_list_slice_end()
(1, 2, 3, 4, 5)
"""
# this doesn't work - it would reassign the array address! # this doesn't work - it would reassign the array address!
# #
#def test_literal_list(): #def test_literal_list():
...@@ -63,54 +6,124 @@ ValueError: Assignment to slice of wrong length, expected 5, got 7 ...@@ -63,54 +6,124 @@ ValueError: Assignment to slice of wrong length, expected 5, got 7
# return (a[0], a[1], a[2], a[3], a[4]) # return (a[0], a[1], a[2], a[3], a[4])
def test_literal_list_slice_all(): def test_literal_list_slice_all():
"""
>>> test_literal_list_slice_all()
(1, 2, 3, 4, 5)
"""
cdef int a[5] # = [5,4,3,2,1] cdef int a[5] # = [5,4,3,2,1]
a[:] = [1,2,3,4,5] a[:] = [1,2,3,4,5]
return (a[0], a[1], a[2], a[3], a[4]) return (a[0], a[1], a[2], a[3], a[4])
def test_literal_list_slice_start(): def test_literal_list_slice_start():
"""
>>> test_literal_list_slice_start()
(1, 2, 3, 4, 5)
"""
cdef int a[7] # = [7,6,5,4,3,2,1] cdef int a[7] # = [7,6,5,4,3,2,1]
a[2:] = [1,2,3,4,5] a[2:] = [1,2,3,4,5]
return (a[2], a[3], a[4], a[5], a[6]) return (a[2], a[3], a[4], a[5], a[6])
def test_literal_list_slice_end(): def test_literal_list_slice_end():
"""
>>> test_literal_list_slice_end()
(1, 2, 3, 4, 5)
"""
cdef int a[7] # = [7,6,5,4,3,2,1] cdef int a[7] # = [7,6,5,4,3,2,1]
a[:5] = [1,2,3,4,5] a[:5] = [1,2,3,4,5]
return (a[0], a[1], a[2], a[3], a[4]) return (a[0], a[1], a[2], a[3], a[4])
def test_literal_list_slice_start_end(): def test_literal_list_slice_start_end():
"""
>>> test_literal_list_slice_start_end()
(1, 2, 3, 4, 5)
"""
cdef int a[9] # = [9,8,7,6,5,4,3,2,1] cdef int a[9] # = [9,8,7,6,5,4,3,2,1]
a[2:7] = [1,2,3,4,5] a[2:7] = [1,2,3,4,5]
return (a[2], a[3], a[4], a[5], a[6]) return (a[2], a[3], a[4], a[5], a[6])
def test_literal_list_slice_start_param(s): def test_literal_list_slice_start_param(s):
"""
>>> test_literal_list_slice_start_param(4)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_param(3)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_param(5)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
"""
cdef int a[9] # = [9,8,7,6,5,4,3,2,1] cdef int a[9] # = [9,8,7,6,5,4,3,2,1]
a[s:] = [1,2,3,4,5] a[s:] = [1,2,3,4,5]
return (a[4], a[5], a[6], a[7], a[8]) return (a[4], a[5], a[6], a[7], a[8])
# return a[s:] # return a[s:]
def test_literal_list_slice_end_param(e): def test_literal_list_slice_end_param(e):
"""
>>> test_literal_list_slice_end_param(5)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_end_param(4)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_end_param(6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
"""
cdef int a[9] # = [9,8,7,6,5,4,3,2,1] cdef int a[9] # = [9,8,7,6,5,4,3,2,1]
a[:e] = [1,2,3,4,5] a[:e] = [1,2,3,4,5]
return (a[0], a[1], a[2], a[3], a[4]) return (a[0], a[1], a[2], a[3], a[4])
# return a[:e] # return a[:e]
def test_literal_list_slice_start_end_param(s,e): def test_literal_list_slice_start_end_param(s,e):
"""
>>> test_literal_list_slice_start_end_param(2,7)
(1, 2, 3, 4, 5)
>>> test_literal_list_slice_start_end_param(3,7)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_start_end_param(1,7)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_end_param(2,6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 4
>>> test_literal_list_slice_start_end_param(2,8)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 6
>>> test_literal_list_slice_start_end_param(3,6)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 3
>>> test_literal_list_slice_start_end_param(1,8)
Traceback (most recent call last):
ValueError: Assignment to slice of wrong length, expected 5, got 7
"""
cdef int a[9] # = [9,8,7,6,5,4,3,2,1] cdef int a[9] # = [9,8,7,6,5,4,3,2,1]
a[s:e] = [1,2,3,4,5] a[s:e] = [1,2,3,4,5]
return (a[2], a[3], a[4], a[5], a[6]) return (a[2], a[3], a[4], a[5], a[6])
# return a[s:e] # return a[s:e]
def test_ptr_literal_list_slice_all(): def test_ptr_literal_list_slice_all():
"""
>>> test_ptr_literal_list_slice_all()
(1, 2, 3, 4, 5)
"""
cdef int *a = [6,5,4,3,2] cdef int *a = [6,5,4,3,2]
a[:] = [1,2,3,4,5] a[:] = [1,2,3,4,5]
return (a[0], a[1], a[2], a[3], a[4]) return (a[0], a[1], a[2], a[3], a[4])
def test_ptr_literal_list_slice_start(): def test_ptr_literal_list_slice_start():
"""
>>> test_ptr_literal_list_slice_start()
(1, 2, 3, 4, 5)
"""
cdef int *a = [6,5,4,3,2,1] cdef int *a = [6,5,4,3,2,1]
a[1:] = [1,2,3,4,5] a[1:] = [1,2,3,4,5]
return (a[1], a[2], a[3], a[4], a[5]) return (a[1], a[2], a[3], a[4], a[5])
def test_ptr_literal_list_slice_end(): def test_ptr_literal_list_slice_end():
"""
>>> test_ptr_literal_list_slice_end()
(1, 2, 3, 4, 5)
"""
cdef int *a = [6,5,4,3,2,1] cdef int *a = [6,5,4,3,2,1]
a[:5] = [1,2,3,4,5] a[:5] = [1,2,3,4,5]
return (a[0], a[1], a[2], a[3], a[4]) return (a[0], a[1], a[2], a[3], a[4])
......
__doc__ = u""" def f():
"""
>>> f() >>> f()
42 42
""" """
def f():
a = 42 a = 42
return a return a
__doc__ = u""" def f(a, b, int i):
"""
>>> f(1, 2, 1) >>> f(1, 2, 1)
>>> f(0, 2, 1) >>> f(0, 2, 1)
Traceback (most recent call last): Traceback (most recent call last):
...@@ -9,17 +10,16 @@ __doc__ = u""" ...@@ -9,17 +10,16 @@ __doc__ = u"""
>>> f(1, 2, 0) >>> f(1, 2, 0)
Traceback (most recent call last): Traceback (most recent call last):
AssertionError AssertionError
"""
>>> g(1, "works")
>>> g(0, "fails")
Traceback (most recent call last):
AssertionError: fails
"""
def f(a, b, int i):
assert a assert a
assert a+b assert a+b
assert i assert i
def g(a, b): def g(a, b):
"""
>>> g(1, "works")
>>> g(0, "fails")
Traceback (most recent call last):
AssertionError: fails
"""
assert a, b assert a, b
...@@ -109,5 +109,3 @@ cdef class MyCdefClass: ...@@ -109,5 +109,3 @@ cdef class MyCdefClass:
>>> True >>> True
False False
""" """
__doc__ = u""" def f(obj2):
"""
>>> f(20) >>> f(20)
'20' '20'
>>> f('test') >>> f('test')
"'test'" "'test'"
"""
>>> g()
'42'
"""
def f(obj2):
obj1 = `obj2` obj1 = `obj2`
return obj1 return obj1
def g(): def g():
"""
>>> g()
'42'
"""
obj1 = `42` obj1 = `42`
return obj1 return obj1
cdef cf(default=None): cdef cf(default=None):
return default return default
......
__doc__ = u"""
>>> viking(5)
5
"""
cdef class Spam: cdef class Spam:
cdef eggs(self, a): cdef eggs(self, a):
return a return a
...@@ -11,4 +6,8 @@ cdef Spam spam(): ...@@ -11,4 +6,8 @@ cdef Spam spam():
return Spam() return Spam()
def viking(a): def viking(a):
"""
>>> viking(5)
5
"""
return spam().eggs(a) return spam().eggs(a)
__doc__ = u""" def test():
"""
>>> test() >>> test()
neg False neg False
pos True pos True
...@@ -6,9 +7,7 @@ __doc__ = u""" ...@@ -6,9 +7,7 @@ __doc__ = u"""
pos pos
neg neg
pos pos
""" """
def test():
cdef long neg = -1 cdef long neg = -1
cdef unsigned long pos = -2 # will be a large positive number cdef unsigned long pos = -2 # will be a large positive number
...@@ -22,4 +21,3 @@ def test(): ...@@ -22,4 +21,3 @@ def test():
print D[neg] print D[neg]
print D[pos] print D[pos]
__doc__ = u"""
>>> call_test()
False
True
False
True
True
True
True
"""
cdef test(bint value): cdef test(bint value):
print value print value
def call_test(): def call_test():
"""
>>> call_test()
False
True
False
True
True
True
True
"""
test(False) test(False)
test(True) test(True)
test(0) test(0)
......
__doc__ = u""" def foo(obj1, obj2, obj3, obj4, obj5):
"""
>>> foo(True, False, 23, 'test', 1) >>> foo(True, False, 23, 'test', 1)
(0.0, 1.0, False, False) (0.0, 1.0, False, False)
""" """
def foo(obj1, obj2, obj3, obj4, obj5):
cdef int bool1, bool2 cdef int bool1, bool2
cdef float bool3, bool4 cdef float bool3, bool4
cdef char *ptr1, *ptr2, *ptr0 cdef char *ptr1, *ptr2, *ptr0
......
...@@ -1392,4 +1392,3 @@ def buffer_nogil(): ...@@ -1392,4 +1392,3 @@ def buffer_nogil():
with nogil: with nogil:
buf[1] = 10 buf[1] = 10
return buf[1] return buf[1]
...@@ -4,11 +4,13 @@ __doc__ = u""" ...@@ -4,11 +4,13 @@ __doc__ = u"""
Traceback (most recent call last): Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'append' AttributeError: 'NoneType' object has no attribute 'append'
>>> append_to_none()
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'append'
""" """
def append_to_none(): def append_to_none():
"""
>>> append_to_none()
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'append'
"""
cdef list l = None cdef list l = None
l.append(2) l.append(2)
__doc__ = u"""
>>> test_c('abc')
fileabc
typeabc
>>> print(test_file_py('abc'))
abc
>>> print(range('abc'))
rangeabc
"""
def test_file_py(file): def test_file_py(file):
assert isinstance(file, (str, unicode)), \ assert isinstance(file, (str, unicode)), \
u"not a string, found '%s' instead" % file.__class__.__name__ u"not a string, found '%s' instead" % file.__class__.__name__
...@@ -28,5 +17,14 @@ cdef type(arg): ...@@ -28,5 +17,14 @@ cdef type(arg):
def test_c(arg): def test_c(arg):
"""
>>> test_c('abc')
fileabc
typeabc
>>> print(test_file_py('abc'))
abc
>>> print(range('abc'))
rangeabc
"""
print test_file_c(arg) print test_file_c(arg)
print type(arg) print type(arg)
__doc__ = u""" cdef class A:
"""
>>> A().test(3) >>> A().test(3)
9 9
""" """
cdef class A:
cdef int (*func_ptr)(int) cdef int (*func_ptr)(int)
......
__doc__ = u"""
>>> test_pos_args(h)
1 2 3 * 0 0
1 2 9 * 2 0
1 2 7 * 2 0
9 8 7 * 0 0
7 8 9 * 0 0
>>> test_kw_args(h)
1 2 3 * 0 0
1 2 9 * 2 1
1 2 7 * 2 1
1 2 9 * 2 2
1 2 9 * 2 2
1 2 9 * 2 3
>>> test_kw_args(e)
2 1
5 1
5 1
5 2
5 2
5 3
>>> test_kw(e)
0 1
0 2
0 2
0 1
>>> test_kw(g)
1
2
2
1
>>> test_pos_args(f)
3
5
5
3
3
>>> test_noargs(e)
0 0
>>> test_noargs(f)
0
>>> test_noargs(g)
0
# and some errors:
>>> test_noargs(h)
Traceback (most recent call last):
TypeError: h() takes at least 3 positional arguments (0 given)
>>> h(1,2, d=5)
Traceback (most recent call last):
TypeError: h() takes at least 3 positional arguments (2 given)
>>> f(1,2, d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
>>> f(1, d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
>>> f(d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
>>> g(1,2, d=5)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (2 given)
>>> g(1,2)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (2 given)
>>> g(1)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (1 given)
>>> test_int_kwargs(e)
Traceback (most recent call last):
TypeError: e() keywords must be strings
>>> test_int_kwargs(f)
Traceback (most recent call last):
TypeError: f() keywords must be strings
>>> test_int_kwargs(g)
Traceback (most recent call last):
TypeError: g() keywords must be strings
>>> test_int_kwargs(h)
Traceback (most recent call last):
TypeError: h() keywords must be strings
>>> d()
Traceback (most recent call last):
TypeError: d() takes at least 1 positional argument (0 given)
>>> d(1)
1 1 0 0
>>> d(1,2)
1 2 0 0
>>> d(1,2,3)
1 2 1 0
>>> d(key=None)
Traceback (most recent call last):
TypeError: d() takes at least 1 positional argument (0 given)
>>> d(1, key=None)
1 1 0 1
>>> d(1,2, key=None)
1 2 0 1
>>> d(1,2,3, key=None)
1 2 1 1
>>> c()
10 20 0
>>> c(1)
1 20 0
>>> c(1,2)
1 2 0
>>> c(key=None)
10 20 1
>>> c(1, key=None)
1 20 1
>>> c(1,2, key=None)
1 2 1
"""
def c(a=10, b=20, **kwds): def c(a=10, b=20, **kwds):
"""
>>> c()
10 20 0
>>> c(1)
1 20 0
>>> c(1,2)
1 2 0
>>> c(key=None)
10 20 1
>>> c(1, key=None)
1 20 1
>>> c(1,2, key=None)
1 2 1
"""
print a, b, len(kwds) print a, b, len(kwds)
def d(a, b=1, *args, **kwds): def d(a, b=1, *args, **kwds):
"""
>>> d()
Traceback (most recent call last):
TypeError: d() takes at least 1 positional argument (0 given)
>>> d(1)
1 1 0 0
>>> d(1,2)
1 2 0 0
>>> d(1,2,3)
1 2 1 0
>>> d(key=None)
Traceback (most recent call last):
TypeError: d() takes at least 1 positional argument (0 given)
>>> d(1, key=None)
1 1 0 1
>>> d(1,2, key=None)
1 2 0 1
>>> d(1,2,3, key=None)
1 2 1 1
"""
print a, b, len(args), len(kwds) print a, b, len(args), len(kwds)
def e(*args, **kwargs): def e(*args, **kwargs):
print len(args), len(kwargs) print len(args), len(kwargs)
def f(*args): def f(*args):
"""
>>> f(1,2, d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
>>> f(1, d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
>>> f(d=5)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'd'
"""
print len(args) print len(args)
def g(**kwargs): def g(**kwargs):
"""
>>> g(1,2, d=5)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (2 given)
>>> g(1,2)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (2 given)
>>> g(1)
Traceback (most recent call last):
TypeError: g() takes exactly 0 positional arguments (1 given)
"""
print len(kwargs) print len(kwargs)
def h(a, b, c, *args, **kwargs): def h(a, b, c, *args, **kwargs):
"""
>>> h(1,2, d=5)
Traceback (most recent call last):
TypeError: h() takes at least 3 positional arguments (2 given)
"""
print a, b, c, u'*', len(args), len(kwargs) print a, b, c, u'*', len(args), len(kwargs)
args = (9,8,7) args = (9,8,7)
...@@ -153,6 +86,22 @@ else: ...@@ -153,6 +86,22 @@ else:
kwargs = {"test" : u"toast"} kwargs = {"test" : u"toast"}
def test_kw_args(f): def test_kw_args(f):
"""
>>> test_kw_args(h)
1 2 3 * 0 0
1 2 9 * 2 1
1 2 7 * 2 1
1 2 9 * 2 2
1 2 9 * 2 2
1 2 9 * 2 3
>>> test_kw_args(e)
2 1
5 1
5 1
5 2
5 2
5 3
"""
f(1,2, c=3) f(1,2, c=3)
f(1,2, d=3, *args) f(1,2, d=3, *args)
f(1,2, d=3, *(7,8,9)) f(1,2, d=3, *(7,8,9))
...@@ -161,6 +110,20 @@ def test_kw_args(f): ...@@ -161,6 +110,20 @@ def test_kw_args(f):
f(1,2, d=3, *args, e=5, **kwargs) f(1,2, d=3, *args, e=5, **kwargs)
def test_pos_args(f): def test_pos_args(f):
"""
>>> test_pos_args(h)
1 2 3 * 0 0
1 2 9 * 2 0
1 2 7 * 2 0
9 8 7 * 0 0
7 8 9 * 0 0
>>> test_pos_args(f)
3
5
5
3
3
"""
f(1,2,3) f(1,2,3)
f(1,2, *args) f(1,2, *args)
f(1,2, *(7,8,9)) f(1,2, *(7,8,9))
...@@ -168,13 +131,52 @@ def test_pos_args(f): ...@@ -168,13 +131,52 @@ def test_pos_args(f):
f(*(7,8,9)) f(*(7,8,9))
def test_kw(f): def test_kw(f):
"""
>>> test_kw(e)
0 1
0 2
0 2
0 1
>>> test_kw(g)
1
2
2
1
"""
f(c=3) f(c=3)
f(d=3, e=5) f(d=3, e=5)
f(d=3, **kwargs) f(d=3, **kwargs)
f(**kwargs) f(**kwargs)
def test_noargs(f): def test_noargs(f):
"""
>>> test_noargs(e)
0 0
>>> test_noargs(f)
0
>>> test_noargs(g)
0
# and some errors:
>>> test_noargs(h)
Traceback (most recent call last):
TypeError: h() takes at least 3 positional arguments (0 given)
"""
f() f()
def test_int_kwargs(f): def test_int_kwargs(f):
"""
>>> test_int_kwargs(e)
Traceback (most recent call last):
TypeError: e() keywords must be strings
>>> test_int_kwargs(f)
Traceback (most recent call last):
TypeError: f() keywords must be strings
>>> test_int_kwargs(g)
Traceback (most recent call last):
TypeError: g() keywords must be strings
>>> test_int_kwargs(h)
Traceback (most recent call last):
TypeError: h() keywords must be strings
"""
f(a=1,b=2,c=3, **{10:20,30:40}) f(a=1,b=2,c=3, **{10:20,30:40})
__doc__ = u"""
>>> test1()
2
>>> test2()
0
>>> test3()
(2, 3)
"""
def test1(): def test1():
"""
>>> test1()
2
"""
cdef int x[2][2] cdef int x[2][2]
x[0][0] = 1 x[0][0] = 1
x[0][1] = 2 x[0][1] = 2
...@@ -20,6 +15,10 @@ cdef int* f(int x[2][2]): ...@@ -20,6 +15,10 @@ cdef int* f(int x[2][2]):
def test2(): def test2():
"""
>>> test2()
0
"""
cdef int a1[5] cdef int a1[5]
cdef int a2[2+3] cdef int a2[2+3]
return sizeof(a1) - sizeof(a2) return sizeof(a1) - sizeof(a2)
...@@ -29,6 +28,10 @@ cdef enum: ...@@ -29,6 +28,10 @@ cdef enum:
MY_SIZE_B = 3 MY_SIZE_B = 3
def test3(): def test3():
"""
>>> test3()
(2, 3)
"""
cdef int a[MY_SIZE_A] cdef int a[MY_SIZE_A]
cdef int b[MY_SIZE_B] cdef int b[MY_SIZE_B]
return sizeof(a)/sizeof(int), sizeof(b)/sizeof(int) return sizeof(a)/sizeof(int), sizeof(b)/sizeof(int)
__doc__ = u"""
>>> foo(True)
True
>>> foo(False)
False
>>> foo('abc') # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
>>> call_cfoo(True)
True
>>> call_cfoo(False)
False
>>> call_cfoo('abc') # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
"""
def foo(bool a): def foo(bool a):
"""
>>> foo(True)
True
>>> foo(False)
False
>>> foo('abc') # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
"""
return a == True return a == True
def call_cfoo(a): def call_cfoo(a):
"""
>>> call_cfoo(True)
True
>>> call_cfoo(False)
False
>>> call_cfoo('abc') # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
"""
return cfoo(a) return cfoo(a)
cdef cfoo(bool a): cdef cfoo(bool a):
......
__doc__ = u"""
>>> cdiv_decorator(-12, 5)
-2
>>> pydiv_decorator(-12, 5)
-3
"""
cimport cython cimport cython
@cython.cdivision(True) @cython.cdivision(True)
cpdef cdiv_decorator(int a, int b): cpdef cdiv_decorator(int a, int b):
"""
>>> cdiv_decorator(-12, 5)
-2
"""
return a / b return a / b
@cython.cdivision(False) @cython.cdivision(False)
cpdef pydiv_decorator(int a, int b): cpdef pydiv_decorator(int a, int b):
"""
>>> pydiv_decorator(-12, 5)
-3
"""
return a / b return a / b
...@@ -7,12 +7,6 @@ __doc__ = u""" ...@@ -7,12 +7,6 @@ __doc__ = u"""
>>> a.foo(10, u'yes') >>> a.foo(10, u'yes')
(True, u'yes') (True, u'yes')
>>> call0()
(True, u'yo')
>>> call1()
(False, u'yo')
>>> call2()
(False, u'go')
""" """
import sys import sys
...@@ -25,13 +19,25 @@ cdef class A: ...@@ -25,13 +19,25 @@ cdef class A:
return a, b return a, b
def call0(): def call0():
"""
>>> call0()
(True, u'yo')
"""
a = A() a = A()
return a.foo() return a.foo()
def call1(): def call1():
"""
>>> call1()
(False, u'yo')
"""
a = A() a = A()
return a.foo(False) return a.foo(False)
def call2(): def call2():
"""
>>> call2()
(False, u'go')
"""
a = A() a = A()
return a.foo(False, u"go") return a.foo(False, u"go")
__doc__ = u'''
>>> no_cdef()
>>> with_cdef()
>>> test_list(list(range(11)), -2, None)
[0, 1, 2, 3, 4, 5, 6, 7, 8, None, 10]
>>> test_list(list(range(11)), "invalid index", None) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: list indices must be integers...
'''
def no_cdef(): def no_cdef():
"""
>>> no_cdef()
"""
lst = list(range(11)) lst = list(range(11))
ob = 10L ob = 10L
lst[ob] = -10 lst[ob] = -10
...@@ -17,6 +9,9 @@ def no_cdef(): ...@@ -17,6 +9,9 @@ def no_cdef():
dd[ob] = -10 dd[ob] = -10
def with_cdef(): def with_cdef():
"""
>>> with_cdef()
"""
cdef list lst = list(range(11)) cdef list lst = list(range(11))
ob = 10L ob = 10L
lst[ob] = -10 lst[ob] = -10
...@@ -24,5 +19,13 @@ def with_cdef(): ...@@ -24,5 +19,13 @@ def with_cdef():
dd[ob] = -10 dd[ob] = -10
def test_list(list L, object i, object a): def test_list(list L, object i, object a):
"""
>>> test_list(list(range(11)), -2, None)
[0, 1, 2, 3, 4, 5, 6, 7, 8, None, 10]
>>> test_list(list(range(11)), "invalid index", None) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: list indices must be integers...
"""
L[i] = a L[i] = a
return L return L
__doc__ = u"""
>>> test(1, 2)
4 1 2 2 0 7 8
"""
cdef int g = 7 cdef int g = 7
def test(x, int y): def test(x, int y):
"""
>>> test(1, 2)
4 1 2 2 0 7 8
"""
if True: if True:
before = 0 before = 0
cdef int a = 4, b = x, c = y, *p = &y cdef int a = 4, b = x, c = y, *p = &y
......
__doc__ = u"""
>>> call2()
>>> call3()
>>> call4()
>>> test_foo()
2
3
7
26
"""
# the calls: # the calls:
def call2(): def call2():
"""
>>> call2()
"""
b(1,2) b(1,2)
def call3(): def call3():
"""
>>> call3()
"""
b(1,2,3) b(1,2,3)
def call4(): def call4():
"""
>>> call4()
"""
b(1,2,3,4) b(1,2,3,4)
# the called function: # the called function:
...@@ -30,6 +28,13 @@ cdef int foo(int a, int b=1, int c=1): ...@@ -30,6 +28,13 @@ cdef int foo(int a, int b=1, int c=1):
return a+b*c return a+b*c
def test_foo(): def test_foo():
"""
>>> test_foo()
2
3
7
26
"""
print foo(1) print foo(1)
print foo(1, 2) print foo(1, 2)
print foo(1, 2, 3) print foo(1, 2, 3)
......
...@@ -36,44 +36,6 @@ True ...@@ -36,44 +36,6 @@ True
>>> import warnings >>> import warnings
>>> warnings.showwarning = simple_warn >>> warnings.showwarning = simple_warn
>>> mod_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-7
>>> div_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-1
>>> complex_expression(-150, 20, 19, -7)
verbose_call(20)
division with oppositely signed operands, C and Python semantics differ
verbose_call(19)
division with oppositely signed operands, C and Python semantics differ
-2
>>> mod_div_zero_int(25, 10, 2)
verbose_call(5)
2
>>> print(mod_div_zero_int(25, 10, 0))
verbose_call(5)
integer division or modulo by zero
>>> print(mod_div_zero_int(25, 0, 0))
integer division or modulo by zero
>>> mod_div_zero_float(25, 10, 2)
2.5
>>> print(mod_div_zero_float(25, 10, 0))
float division
>>> print(mod_div_zero_float(25, 0, 0))
float divmod()
>>> py_div_long(-5, -1)
5
>>> import sys
>>> maxint = getattr(sys, ((sys.version_info[0] >= 3) and 'maxsize' or 'maxint'))
>>> py_div_long(-maxint-1, -1)
Traceback (most recent call last):
...
OverflowError: value too large to perform division
""" """
def _all(seq): def _all(seq):
...@@ -137,16 +99,34 @@ def test_cdiv_cmod(short a, short b): ...@@ -137,16 +99,34 @@ def test_cdiv_cmod(short a, short b):
@cython.cdivision(True) @cython.cdivision(True)
@cython.cdivision_warnings(True) @cython.cdivision_warnings(True)
def mod_int_c_warn(int a, int b): def mod_int_c_warn(int a, int b):
"""
>>> mod_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-7
"""
return a % b return a % b
@cython.cdivision(True) @cython.cdivision(True)
@cython.cdivision_warnings(True) @cython.cdivision_warnings(True)
def div_int_c_warn(int a, int b): def div_int_c_warn(int a, int b):
"""
>>> div_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-1
"""
return a // b return a // b
@cython.cdivision(False) @cython.cdivision(False)
@cython.cdivision_warnings(True) @cython.cdivision_warnings(True)
def complex_expression(int a, int b, int c, int d): def complex_expression(int a, int b, int c, int d):
"""
>>> complex_expression(-150, 20, 19, -7)
verbose_call(20)
division with oppositely signed operands, C and Python semantics differ
verbose_call(19)
division with oppositely signed operands, C and Python semantics differ
-2
"""
return (a // verbose_call(b)) % (verbose_call(c) // d) return (a // verbose_call(b)) % (verbose_call(c) // d)
cdef int verbose_call(int x): cdef int verbose_call(int x):
...@@ -158,6 +138,16 @@ cdef int verbose_call(int x): ...@@ -158,6 +138,16 @@ cdef int verbose_call(int x):
@cython.cdivision(False) @cython.cdivision(False)
def mod_div_zero_int(int a, int b, int c): def mod_div_zero_int(int a, int b, int c):
"""
>>> mod_div_zero_int(25, 10, 2)
verbose_call(5)
2
>>> print(mod_div_zero_int(25, 10, 0))
verbose_call(5)
integer division or modulo by zero
>>> print(mod_div_zero_int(25, 0, 0))
integer division or modulo by zero
"""
try: try:
return verbose_call(a % b) / c return verbose_call(a % b) / c
except ZeroDivisionError, ex: except ZeroDivisionError, ex:
...@@ -165,6 +155,14 @@ def mod_div_zero_int(int a, int b, int c): ...@@ -165,6 +155,14 @@ def mod_div_zero_int(int a, int b, int c):
@cython.cdivision(False) @cython.cdivision(False)
def mod_div_zero_float(float a, float b, float c): def mod_div_zero_float(float a, float b, float c):
"""
>>> mod_div_zero_float(25, 10, 2)
2.5
>>> print(mod_div_zero_float(25, 10, 0))
float division
>>> print(mod_div_zero_float(25, 0, 0))
float divmod()
"""
try: try:
return (a % b) / c return (a % b) / c
except ZeroDivisionError, ex: except ZeroDivisionError, ex:
...@@ -172,4 +170,14 @@ def mod_div_zero_float(float a, float b, float c): ...@@ -172,4 +170,14 @@ def mod_div_zero_float(float a, float b, float c):
@cython.cdivision(False) @cython.cdivision(False)
def py_div_long(long a, long b): def py_div_long(long a, long b):
"""
>>> py_div_long(-5, -1)
5
>>> import sys
>>> maxint = getattr(sys, ((sys.version_info[0] >= 3) and 'maxsize' or 'maxint'))
>>> py_div_long(-maxint-1, -1)
Traceback (most recent call last):
...
OverflowError: value too large to perform division
"""
return a / b return a / b
__doc__ = u"""
>>> test()
"""
cdef void ftang(): cdef void ftang():
cdef int x cdef int x
x = 0 x = 0
...@@ -16,6 +12,9 @@ cdef spam(int i, obj, object object): ...@@ -16,6 +12,9 @@ cdef spam(int i, obj, object object):
c = 0 c = 0
def test(): def test():
"""
>>> test()
"""
ftang() ftang()
foo(0, c'f') foo(0, c'f')
spam(25, None, None) spam(25, None, None)
__doc__ = u"""
>>> global_c_and_s()
99
abcdef
>>> local_c_and_s()
98
bcdefg
"""
cdef char c = 'c' cdef char c = 'c'
cdef char* s = 'abcdef' cdef char* s = 'abcdef'
def global_c_and_s(): def global_c_and_s():
"""
>>> global_c_and_s()
99
abcdef
"""
pys = s pys = s
print c print c
print (pys.decode(u'ASCII')) print (pys.decode(u'ASCII'))
def local_c_and_s(): def local_c_and_s():
"""
>>> local_c_and_s()
98
bcdefg
"""
cdef char c = 'b' cdef char c = 'b'
cdef char* s = 'bcdefg' cdef char* s = 'bcdefg'
pys = s pys = s
......
...@@ -13,11 +13,13 @@ __doc__ = u""" ...@@ -13,11 +13,13 @@ __doc__ = u"""
>>> (int1, long1) == f() >>> (int1, long1) == f()
True True
>>> f()
(45, 111)
""" """
def f(): def f():
"""
>>> f()
(45, 111)
"""
cdef int int1, int2, int3 cdef int int1, int2, int3
cdef char char1 cdef char char1
cdef long long1, long2 cdef long long1, long2
......
__doc__ = u""" def single_py(a, b):
"""
>>> single_py(1, 2) >>> single_py(1, 2)
True True
>>> single_py(2, 1) >>> single_py(2, 1)
False False
"""
return a < b
def cascaded_py(a, b, c):
"""
>>> cascaded_py(1, 2, 3) >>> cascaded_py(1, 2, 3)
True True
>>> cascaded_py(1, 2, -1) >>> cascaded_py(1, 2, -1)
False False
>>> cascaded_py(10, 2, 3) >>> cascaded_py(10, 2, 3)
False False
"""
return a < b < c
def single_c(int a, int b):
"""
>>> single_c(1, 2) >>> single_c(1, 2)
True True
>>> single_c(2, 1) >>> single_c(2, 1)
False False
"""
return a < b
def cascaded_c(double a, double b, double c):
"""
>>> cascaded_c(1, 2, 3) >>> cascaded_c(1, 2, 3)
True True
>>> cascaded_c(1, 2, -1) >>> cascaded_c(1, 2, -1)
False False
>>> cascaded_c(10, 2, 3) >>> cascaded_c(10, 2, 3)
False False
""" """
def single_py(a, b):
return a < b
def cascaded_py(a, b, c):
return a < b < c
def single_c(int a, int b):
return a < b
def cascaded_c(double a, double b, double c):
return a < b < c return a < b < c
def typed_cmp(list L): def typed_cmp(list L):
......
cdef char* cstring = "abcdefg" cdef char* cstring = "abcdefg"
cdef void spam(char *target): cdef void spam(char *target):
......
__doc__ = u""" #cdef extern from "complex.h":
# pass
cimport cython
def test_object_conversion(o):
"""
>>> test_object_conversion(2) >>> test_object_conversion(2)
((2+0j), (2+0j), (2+0j)) ((2+0j), (2+0j), (2+0j))
>>> test_object_conversion(2j - 0.5) >>> test_object_conversion(2j - 0.5)
((-0.5+2j), (-0.5+2j), (-0.5+2j)) ((-0.5+2j), (-0.5+2j), (-0.5+2j))
"""
cdef float complex a = o
cdef double complex b = o
cdef long double complex c = o
return (a, b, c)
def test_arithmetic(double complex z, double complex w):
"""
>>> test_arithmetic(2j, 4j) >>> test_arithmetic(2j, 4j)
(2j, -2j, 6j, -2j, (-8+0j), (0.5+0j)) (2j, -2j, 6j, -2j, (-8+0j), (0.5+0j))
>>> test_arithmetic(6+12j, 3j) >>> test_arithmetic(6+12j, 3j)
((6+12j), (-6-12j), (6+15j), (6+9j), (-36+18j), (4-2j)) ((6+12j), (-6-12j), (6+15j), (6+9j), (-36+18j), (4-2j))
>>> test_arithmetic(5-10j, 3+4j) >>> test_arithmetic(5-10j, 3+4j)
((5-10j), (-5+10j), (8-6j), (2-14j), (55-10j), (-1-2j)) ((5-10j), (-5+10j), (8-6j), (2-14j), (55-10j), (-1-2j))
## XXX this is not working
## >>> test_div_by_zero(4j)
## -0.25j
## >>> test_div_by_zero(0)
## Traceback (most recent call last):
## ...
## ZeroDivisionError: float division
"""
return +z, -z, z+w, z-w, z*w, z/w
## XXX this is not working ## XXX this is not working
## >>> test_div_by_zero(4j) ## @cython.cdivision(False)
## -0.25j ## def test_div_by_zero(double complex z):
## >>> test_div_by_zero(0) ## return 1/z
## Traceback (most recent call last):
## ...
## ZeroDivisionError: float division
def test_coercion(int a, float b, double c, float complex d, double complex e):
"""
>>> test_coercion(1, 1.5, 2.5, 4+1j, 10j) >>> test_coercion(1, 1.5, 2.5, 4+1j, 10j)
(1+0j) (1+0j)
(1.5+0j) (1.5+0j)
...@@ -26,7 +48,17 @@ __doc__ = u""" ...@@ -26,7 +48,17 @@ __doc__ = u"""
(4+1j) (4+1j)
10j 10j
(9+21j) (9+21j)
"""
cdef double complex z
z = a; print z
z = b; print z
z = c; print z
z = d; print z
z = e; print z
return z + a + b + c + d + e
def test_compare(double complex a, double complex b):
"""
>>> test_compare(3, 3) >>> test_compare(3, 3)
(True, False) (True, False)
>>> test_compare(3j, 3j) >>> test_compare(3j, 3j)
...@@ -35,93 +67,62 @@ __doc__ = u""" ...@@ -35,93 +67,62 @@ __doc__ = u"""
(False, True) (False, True)
>>> test_compare(3, 4) >>> test_compare(3, 4)
(False, True) (False, True)
"""
return a == b, a != b
def test_compare_coerce(double complex a, int b):
"""
>>> test_compare_coerce(3, 4) >>> test_compare_coerce(3, 4)
(False, True) (False, True)
>>> test_compare_coerce(4+1j, 4) >>> test_compare_coerce(4+1j, 4)
(False, True) (False, True)
>>> test_compare_coerce(4, 4) >>> test_compare_coerce(4, 4)
(True, False) (True, False)
"""
return a == b, a != b
def test_literal():
"""
>>> test_literal() >>> test_literal()
(5j, (1-2.5j)) (5j, (1-2.5j))
"""
return 5j, 1-2.5j
def test_real_imag(double complex z):
"""
>>> test_real_imag(1-3j) >>> test_real_imag(1-3j)
(1.0, -3.0) (1.0, -3.0)
>>> test_real_imag(5) >>> test_real_imag(5)
(5.0, 0.0) (5.0, 0.0)
>>> test_real_imag(1.5j) >>> test_real_imag(1.5j)
(0.0, 1.5) (0.0, 1.5)
"""
return z.real, z.imag
def test_real_imag_assignment(object a, double b):
"""
>>> test_real_imag_assignment(1, 2) >>> test_real_imag_assignment(1, 2)
(1+2j) (1+2j)
>>> test_real_imag_assignment(1.5, -3.5) >>> test_real_imag_assignment(1.5, -3.5)
(1.5-3.5j) (1.5-3.5j)
"""
>>> test_conjugate(2+3j)
(2-3j)
>>> test_conjugate_double(2+3j)
(2-3j)
>>> test_coerce_typedef_multiply(3, 1j)
(3j)
>>> complex_retval()
1j
"""
#cdef extern from "complex.h":
# pass
cimport cython
def test_object_conversion(o):
cdef float complex a = o
cdef double complex b = o
cdef long double complex c = o
return (a, b, c)
def test_arithmetic(double complex z, double complex w):
return +z, -z, z+w, z-w, z*w, z/w
## XXX this is not working
## @cython.cdivision(False)
## def test_div_by_zero(double complex z):
## return 1/z
def test_coercion(int a, float b, double c, float complex d, double complex e):
cdef double complex z
z = a; print z
z = b; print z
z = c; print z
z = d; print z
z = e; print z
return z + a + b + c + d + e
def test_compare(double complex a, double complex b):
return a == b, a != b
def test_compare_coerce(double complex a, int b):
return a == b, a != b
def test_literal():
return 5j, 1-2.5j
def test_real_imag(double complex z):
return z.real, z.imag
def test_real_imag_assignment(object a, double b):
cdef double complex z cdef double complex z
z.real = a z.real = a
z.imag = b z.imag = b
return z return z
def test_conjugate(float complex z): def test_conjugate(float complex z):
"""
>>> test_conjugate(2+3j)
(2-3j)
"""
return z.conjugate() return z.conjugate()
def test_conjugate_double(double complex z): def test_conjugate_double(double complex z):
"""
>>> test_conjugate_double(2+3j)
(2-3j)
"""
return z.conjugate() return z.conjugate()
ctypedef double complex cdouble ctypedef double complex cdouble
...@@ -130,7 +131,15 @@ def test_conjugate_typedef(cdouble z): ...@@ -130,7 +131,15 @@ def test_conjugate_typedef(cdouble z):
ctypedef double mydouble ctypedef double mydouble
def test_coerce_typedef_multiply(mydouble x, double complex z): def test_coerce_typedef_multiply(mydouble x, double complex z):
"""
>>> test_coerce_typedef_multiply(3, 1j)
(3j)
"""
return x * z return x * z
cpdef double complex complex_retval(): cpdef double complex complex_retval():
"""
>>> complex_retval()
1j
"""
return 1j return 1j
...@@ -8,4 +8,3 @@ if sys.version_info[0] >= 3: ...@@ -8,4 +8,3 @@ if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '") __doc__ = __doc__.replace(u" u'", u" '")
spam = u"C string 1" + u"C string 2" spam = u"C string 1" + u"C string 2"
__doc__ = u"""
>>> add() == 1+2+3+4
True
>>> add_var(10) == 1+2+10+3+4
True
>>> neg() == -1 -2 - (-3+4)
True
>>> long_int_mix() == 1 + (2 * 3) // 2
True
>>> if IS_PY3: type(long_int_mix()) is int
... else: type(long_int_mix()) is long
True
>>> char_int_mix() == 1 + (ord(' ') * 3) // 2 + ord('A')
True
>>> int_cast() == 1 + 2 * 6000
True
>>> mul() == 1*60*1000
True
>>> arithm() == 9*2+3*8//6-10
True
>>> parameters() == _func(-1 -2, - (-3+4), 1*2*3)
True
>>> lists() == [1,2,3] + [4,5,6]
True
"""
import sys import sys
IS_PY3 = sys.version_info[0] >= 3 IS_PY3 = sys.version_info[0] >= 3
...@@ -31,31 +5,74 @@ def _func(a,b,c): ...@@ -31,31 +5,74 @@ def _func(a,b,c):
return a+b+c return a+b+c
def add(): def add():
"""
>>> add() == 1+2+3+4
True
"""
return 1+2+3+4 return 1+2+3+4
def add_var(a): def add_var(a):
"""
>>> add_var(10) == 1+2+10+3+4
True
"""
return 1+2 +a+ 3+4 return 1+2 +a+ 3+4
def neg(): def neg():
"""
>>> neg() == -1 -2 - (-3+4)
True
"""
return -1 -2 - (-3+4) return -1 -2 - (-3+4)
def long_int_mix(): def long_int_mix():
"""
>>> long_int_mix() == 1 + (2 * 3) // 2
True
>>> if IS_PY3: type(long_int_mix()) is int
... else: type(long_int_mix()) is long
True
"""
return 1L + (2 * 3L) // 2 return 1L + (2 * 3L) // 2
def char_int_mix(): def char_int_mix():
"""
>>> char_int_mix() == 1 + (ord(' ') * 3) // 2 + ord('A')
True
"""
return 1L + (c' ' * 3L) // 2 + c'A' return 1L + (c' ' * 3L) // 2 + c'A'
def int_cast(): def int_cast():
"""
>>> int_cast() == 1 + 2 * 6000
True
"""
return <int>(1 + 2 * 6000) return <int>(1 + 2 * 6000)
def mul(): def mul():
"""
>>> mul() == 1*60*1000
True
"""
return 1*60*1000 return 1*60*1000
def arithm(): def arithm():
"""
>>> arithm() == 9*2+3*8//6-10
True
"""
return 9*2+3*8//6-10 return 9*2+3*8//6-10
def parameters(): def parameters():
"""
>>> parameters() == _func(-1 -2, - (-3+4), 1*2*3)
True
"""
return _func(-1 -2, - (-3+4), 1*2*3) return _func(-1 -2, - (-3+4), 1*2*3)
def lists(): def lists():
"""
>>> lists() == [1,2,3] + [4,5,6]
True
"""
return [1,2,3] + [4,5,6] return [1,2,3] + [4,5,6]
__doc__ = """ cdef class A:
"""
>>> A().is_True() >>> A().is_True()
True True
>>> A().is_False() >>> A().is_False()
False False
"""
>>> B().is_True()
True
>>> B().is_False()
False
"""
cdef class A:
cpdef is_True(self): cpdef is_True(self):
return True return True
cpdef is_False(self): cpdef is_False(self):
return not self.is_True() return not self.is_True()
class B(A): class B(A):
"""
>>> B().is_True()
True
>>> B().is_False()
False
"""
def is_True(self): def is_True(self):
return True return True
__doc__ = """
>>> f()
{'x': 1}
"""
cimport crashT245_pxd cimport crashT245_pxd
def f(): def f():
"""
>>> f()
{'x': 1}
"""
cdef crashT245_pxd.MyStruct s cdef crashT245_pxd.MyStruct s
s.x = 1 s.x = 1
print s print s
__doc__ = u"""
>>> test_i()
>>> test_c()
>>> test_p()
>>> test_g()
"""
cdef struct Grail cdef struct Grail
cdef struct Spam: cdef struct Spam:
...@@ -41,19 +34,31 @@ cdef void eggs_g(Spam s): ...@@ -41,19 +34,31 @@ cdef void eggs_g(Spam s):
spam = ham spam = ham
def test_i(): def test_i():
"""
>>> test_i()
"""
spam.i = 1 spam.i = 1
eggs_i(spam) eggs_i(spam)
def test_c(): def test_c():
"""
>>> test_c()
"""
spam.c = c'a' spam.c = c'a'
eggs_c(spam) eggs_c(spam)
def test_p(): def test_p():
"""
>>> test_p()
"""
cdef float f cdef float f
spam.p[0] = &f spam.p[0] = &f
eggs_p(spam) eggs_p(spam)
def test_g(): def test_g():
"""
>>> test_g()
"""
cdef Grail l cdef Grail l
spam.g = &l spam.g = &l
eggs_g(spam) eggs_g(spam)
__doc__ = u"""
>>> f()
1
>>> g()
2
>>> h()
3
"""
DEF NO = 0 DEF NO = 0
DEF YES = 1 DEF YES = 1
def f(): def f():
"""
>>> f()
1
"""
cdef int i cdef int i
IF YES: IF YES:
i = 1 i = 1
...@@ -21,6 +16,10 @@ def f(): ...@@ -21,6 +16,10 @@ def f():
return i return i
def g(): def g():
"""
>>> g()
2
"""
cdef int i cdef int i
IF NO: IF NO:
i = 1 i = 1
...@@ -31,6 +30,10 @@ def g(): ...@@ -31,6 +30,10 @@ def g():
return i return i
def h(): def h():
"""
>>> h()
3
"""
cdef int i cdef int i
IF NO: IF NO:
i = 1 i = 1
......
__doc__ = u"""
>>> test_int(0)
False
>>> test_int(1)
True
>>> test_short(0)
False
>>> test_short(1)
True
>>> test_Py_ssize_t(0)
False
>>> test_Py_ssize_t(1)
True
>>> test_ptr()
False
>>> test_ptr2()
2
>>> test_attr_int(TestExtInt(0))
False
>>> test_attr_int(TestExtInt(1))
True
>>> test_attr_ptr(TestExtPtr(0))
False
>>> test_attr_ptr(TestExtPtr(1))
True
"""
def test_ptr(): def test_ptr():
"""
>>> test_ptr()
False
"""
cdef void* p = NULL cdef void* p = NULL
if p: if p:
return True return True
...@@ -38,6 +10,10 @@ def test_ptr(): ...@@ -38,6 +10,10 @@ def test_ptr():
return False return False
def test_ptr2(): def test_ptr2():
"""
>>> test_ptr2()
2
"""
cdef char* p1 = NULL cdef char* p1 = NULL
cdef char* p2 = NULL cdef char* p2 = NULL
p1 += 1 p1 += 1
...@@ -50,18 +26,36 @@ def test_ptr2(): ...@@ -50,18 +26,36 @@ def test_ptr2():
return 3 return 3
def test_int(int i): def test_int(int i):
"""
>>> test_int(0)
False
>>> test_int(1)
True
"""
if i: if i:
return True return True
else: else:
return False return False
def test_short(short i): def test_short(short i):
"""
>>> test_short(0)
False
>>> test_short(1)
True
"""
if i: if i:
return True return True
else: else:
return False return False
def test_Py_ssize_t(Py_ssize_t i): def test_Py_ssize_t(Py_ssize_t i):
"""
>>> test_Py_ssize_t(0)
False
>>> test_Py_ssize_t(1)
True
"""
if i: if i:
return True return True
else: else:
...@@ -72,6 +66,12 @@ cdef class TestExtInt: ...@@ -72,6 +66,12 @@ cdef class TestExtInt:
def __init__(self, i): self.i = i def __init__(self, i): self.i = i
def test_attr_int(TestExtInt e): def test_attr_int(TestExtInt e):
"""
>>> test_attr_int(TestExtInt(0))
False
>>> test_attr_int(TestExtInt(1))
True
"""
if e.i: if e.i:
return True return True
else: else:
...@@ -82,6 +82,12 @@ cdef class TestExtPtr: ...@@ -82,6 +82,12 @@ cdef class TestExtPtr:
def __init__(self, int i): self.p = <void*>i def __init__(self, int i): self.p = <void*>i
def test_attr_ptr(TestExtPtr e): def test_attr_ptr(TestExtPtr e):
"""
>>> test_attr_ptr(TestExtPtr(0))
False
>>> test_attr_ptr(TestExtPtr(1))
True
"""
if e.p: if e.p:
return True return True
else: else:
......
__doc__ = u"""
>>> test_i()
>>> test_c()
>>> test_p()
"""
cdef union Spam: cdef union Spam:
int i int i
char c char c
...@@ -29,14 +23,23 @@ cdef void eggs_p(Spam s): ...@@ -29,14 +23,23 @@ cdef void eggs_p(Spam s):
spam = ham spam = ham
def test_i(): def test_i():
"""
>>> test_i()
"""
spam.i = 1 spam.i = 1
eggs_i(spam) eggs_i(spam)
def test_c(): def test_c():
"""
>>> test_c()
"""
spam.c = c'a' spam.c = c'a'
eggs_c(spam) eggs_c(spam)
def test_p(): def test_p():
"""
>>> test_p()
"""
cdef float f cdef float f
spam.p[0] = &f spam.p[0] = &f
eggs_p(spam) eggs_p(spam)
__doc__ = u"""
>>> f()
"""
def f(): def f():
"""
>>> f()
"""
cdef char a_char cdef char a_char
cdef short a_short cdef short a_short
cdef int i1, i2 cdef int i1, i2
......
__doc__ = u""" def empty():
"""
>>> empty() >>> empty()
{} {}
"""
d = {}
return d
def keyvalue(key, value):
"""
>>> keyvalue(1, 2) >>> keyvalue(1, 2)
{1: 2} {1: 2}
"""
d = {key:value}
return d
def keyvalues(key1, value1, key2, value2):
"""
>>> keyvalues(1, 2, 3, 4) >>> keyvalues(1, 2, 3, 4)
{1: 2, 3: 4} {1: 2, 3: 4}
"""
d = {key1:value1, key2:value2}
return d
def keyvalues2(key1, value1, key2, value2):
"""
>>> keyvalues2(1, 2, 3, 4) >>> keyvalues2(1, 2, 3, 4)
{1: 2, 3: 4} {1: 2, 3: 4}
"""
d = {key1:value1, key2:value2,}
return d
def constant():
"""
>>> len(constant()) >>> len(constant())
2 2
>>> print(constant()['parrot']) >>> print(constant()['parrot'])
resting resting
>>> print(constant()['answer']) >>> print(constant()['answer'])
42 42
"""
d = {u"parrot":u"resting", u"answer":42}
return d
def dict_call():
"""
>>> print(dict_call()['parrot']) >>> print(dict_call()['parrot'])
resting resting
>>> print(dict_call()['answer']) >>> print(dict_call()['answer'])
42 42
"""
d = dict(parrot=u"resting", answer=42)
return d
def dict_call_dict():
"""
>>> print(dict_call_dict()['parrot']) >>> print(dict_call_dict()['parrot'])
resting resting
>>> print(dict_call_dict()['answer']) >>> print(dict_call_dict()['answer'])
42 42
"""
d = dict(dict(parrot=u"resting", answer=42))
return d
def dict_call_kwargs():
"""
>>> print(dict_call_kwargs()['parrot1']) >>> print(dict_call_kwargs()['parrot1'])
resting resting
>>> print(dict_call_kwargs()['parrot2']) >>> print(dict_call_kwargs()['parrot2'])
...@@ -34,37 +72,7 @@ __doc__ = u""" ...@@ -34,37 +72,7 @@ __doc__ = u"""
42 42
>>> print(dict_call_kwargs()['answer2']) >>> print(dict_call_kwargs()['answer2'])
42 42
""" """
def empty():
d = {}
return d
def keyvalue(key, value):
d = {key:value}
return d
def keyvalues(key1, value1, key2, value2):
d = {key1:value1, key2:value2}
return d
def keyvalues2(key1, value1, key2, value2):
d = {key1:value1, key2:value2,}
return d
def constant():
d = {u"parrot":u"resting", u"answer":42}
return d
def dict_call():
d = dict(parrot=u"resting", answer=42)
return d
def dict_call_dict():
d = dict(dict(parrot=u"resting", answer=42))
return d
def dict_call_kwargs():
kwargs = dict(parrot1=u"resting", answer1=42) kwargs = dict(parrot1=u"resting", answer1=42)
d = dict(parrot2=u"resting", answer2=42, **kwargs) d = dict(parrot2=u"resting", answer2=42, **kwargs)
return d return d
__doc__ = u"""
>>> test_get_char_neg()
0
>>> test_get_char_zero()
1
>>> test_get_char_pos()
2
>>> test_get_uchar_zero()
1
>>> test_get_uchar_pos()
2
>>> test_get_int_neg()
0
>>> test_get_int_zero()
1
>>> test_get_int_pos()
2
>>> test_get_uint_zero()
1
>>> test_get_uint_pos()
2
>>> test_get_longlong_neg()
0
>>> test_get_longlong_zero()
1
>>> test_get_longlong_pos()
2
>>> test_get_longlong_big()
3
>>> test_get_ulonglong_zero()
1
>>> test_get_ulonglong_pos()
2
>>> test_get_ulonglong_big()
3
>>> test_del_char()
Traceback (most recent call last):
KeyError: 0
>>> test_del_uchar()
Traceback (most recent call last):
KeyError: 0
>>> test_del_int()
Traceback (most recent call last):
KeyError: 0
>>> test_del_uint() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
>>> test_del_longlong() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
>>> test_del_longlong_big() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
>>> test_del_ulonglong() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
>>> test_del_ulonglong_big() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
"""
def test_get_char_neg(): def test_get_char_neg():
"""
>>> test_get_char_neg()
0
"""
cdef char key = -1 cdef char key = -1
d = {-1:0} d = {-1:0}
return d[key] return d[key]
def test_get_char_zero(): def test_get_char_zero():
"""
>>> test_get_char_zero()
1
"""
cdef char key = 0 cdef char key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_char_pos(): def test_get_char_pos():
"""
>>> test_get_char_pos()
2
"""
cdef char key = 1 cdef char key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_uchar_zero(): def test_get_uchar_zero():
"""
>>> test_get_uchar_zero()
1
"""
cdef unsigned char key = 0 cdef unsigned char key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_uchar_pos(): def test_get_uchar_pos():
"""
>>> test_get_uchar_pos()
2
"""
cdef unsigned char key = 1 cdef unsigned char key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_int_neg(): def test_get_int_neg():
"""
>>> test_get_int_neg()
0
"""
cdef int key = -1 cdef int key = -1
d = {-1:0} d = {-1:0}
return d[key] return d[key]
def test_get_int_zero(): def test_get_int_zero():
"""
>>> test_get_int_zero()
1
"""
cdef int key = 0 cdef int key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_int_pos(): def test_get_int_pos():
"""
>>> test_get_int_pos()
2
"""
cdef int key = 1 cdef int key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_uint_zero(): def test_get_uint_zero():
"""
>>> test_get_uint_zero()
1
"""
cdef unsigned int key = 0 cdef unsigned int key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_uint_pos(): def test_get_uint_pos():
"""
>>> test_get_uint_pos()
2
"""
cdef unsigned int key = 1 cdef unsigned int key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_longlong_neg(): def test_get_longlong_neg():
"""
>>> test_get_longlong_neg()
0
"""
cdef long long key = -1 cdef long long key = -1
d = {-1:0} d = {-1:0}
return d[key] return d[key]
def test_get_longlong_zero(): def test_get_longlong_zero():
"""
>>> test_get_longlong_zero()
1
"""
cdef long long key = 0 cdef long long key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_longlong_pos(): def test_get_longlong_pos():
"""
>>> test_get_longlong_pos()
2
"""
cdef long long key = 1 cdef long long key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_longlong_big(): def test_get_longlong_big():
"""
>>> test_get_longlong_big()
3
"""
cdef unsigned int shift = sizeof(long)+2 cdef unsigned int shift = sizeof(long)+2
cdef long long big = 1 cdef long long big = 1
cdef long long key = big<<shift cdef long long key = big<<shift
...@@ -127,14 +122,26 @@ def test_get_longlong_big(): ...@@ -127,14 +122,26 @@ def test_get_longlong_big():
return d[key] return d[key]
def test_get_ulonglong_zero(): def test_get_ulonglong_zero():
"""
>>> test_get_ulonglong_zero()
1
"""
cdef unsigned long long key = 0 cdef unsigned long long key = 0
d = {0:1} d = {0:1}
return d[key] return d[key]
def test_get_ulonglong_pos(): def test_get_ulonglong_pos():
"""
>>> test_get_ulonglong_pos()
2
"""
cdef unsigned long long key = 1 cdef unsigned long long key = 1
d = {1:2} d = {1:2}
return d[key] return d[key]
def test_get_ulonglong_big(): def test_get_ulonglong_big():
"""
>>> test_get_ulonglong_big()
3
"""
cdef unsigned int shift = sizeof(long)+2 cdef unsigned int shift = sizeof(long)+2
cdef unsigned long long big = 1 cdef unsigned long long big = 1
cdef unsigned long long key = big<<shift cdef unsigned long long key = big<<shift
...@@ -143,42 +150,77 @@ def test_get_ulonglong_big(): ...@@ -143,42 +150,77 @@ def test_get_ulonglong_big():
def test_del_char(): def test_del_char():
"""
>>> test_del_char()
Traceback (most recent call last):
KeyError: 0
"""
cdef char key = 0 cdef char key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_uchar(): def test_del_uchar():
"""
>>> test_del_uchar()
Traceback (most recent call last):
KeyError: 0
"""
cdef unsigned char key = 0 cdef unsigned char key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_int(): def test_del_int():
"""
>>> test_del_int()
Traceback (most recent call last):
KeyError: 0
"""
cdef int key = 0 cdef int key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_uint(): def test_del_uint():
"""
>>> test_del_uint() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
"""
cdef unsigned int key = 0 cdef unsigned int key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_longlong(): def test_del_longlong():
"""
>>> test_del_longlong() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
"""
cdef long long key = 0 cdef long long key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_ulonglong(): def test_del_ulonglong():
"""
>>> test_del_ulonglong() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: 0...
"""
cdef unsigned long long key = 0 cdef unsigned long long key = 0
d = {0:1} d = {0:1}
del d[key] del d[key]
return d[key] return d[key]
def test_del_longlong_big(): def test_del_longlong_big():
"""
>>> test_del_longlong_big() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
"""
cdef int shift = sizeof(long)+2 cdef int shift = sizeof(long)+2
cdef long long big = 1 cdef long long big = 1
cdef long long key = big<<shift cdef long long key = big<<shift
...@@ -187,6 +229,11 @@ def test_del_longlong_big(): ...@@ -187,6 +229,11 @@ def test_del_longlong_big():
return d[key] return d[key]
def test_del_ulonglong_big(): def test_del_ulonglong_big():
"""
>>> test_del_ulonglong_big() #doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
"""
cdef unsigned int shift = sizeof(long)+2 cdef unsigned int shift = sizeof(long)+2
cdef unsigned long long big = 1 cdef unsigned long long big = 1
cdef unsigned long long key = big<<shift cdef unsigned long long key = big<<shift
......
__doc__ = u""" def test():
"""
>>> test() >>> test()
1.0 1.0
""" """
def test():
cdef float v[10][10] cdef float v[10][10]
v[1][2] = 1.0 v[1][2] = 1.0
return v[1][2] return v[1][2]
__doc__ = u"""
>>> go_py_empty()
20
>>> go_c_empty()
20
"""
def go_py_empty(): def go_py_empty():
"""
>>> go_py_empty()
20
"""
i = 20 i = 20
for i in range(4,0): for i in range(4,0):
print u"Spam!" print u"Spam!"
return i return i
def go_c_empty(): def go_c_empty():
"""
>>> go_c_empty()
20
"""
cdef int i = 20 cdef int i = 20
for i in range(4,0): for i in range(4,0):
print u"Spam!" print u"Spam!"
......
__doc__ = u"""
>>> go_c_enumerate()
0 1
1 2
2 3
3 4
>>> go_py_enumerate()
0 1
1 2
2 3
3 4
>>> empty_c_enumerate()
(55, 99)
>>> go_c_enumerate_step()
0 1
1 3
2 5
>>> single_target_enumerate()
0 1
1 2
2 3
3 4
>>> multi_enumerate()
0 0 0 1
1 1 1 2
2 2 2 3
3 3 3 4
>>> multi_c_enumerate()
0 0 0 1
1 1 1 2
2 2 2 3
3 3 3 4
>>> py_enumerate_break(1,2,3,4)
0 1
:: 0 1
>>> py_enumerate_return()
:: 55 99
>>> py_enumerate_return(1,2,3,4)
0 1
>>> py_enumerate_continue(1,2,3,4)
0 1
1 2
2 3
3 4
:: 3 4
>>> py_enumerate_dict({})
:: 55 99
>>> py_enumerate_dict(dict(a=1, b=2, c=3))
0 a
1 c
2 b
:: 2 b
"""
cimport cython cimport cython
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def go_py_enumerate(): def go_py_enumerate():
"""
>>> go_py_enumerate()
0 1
1 2
2 3
3 4
"""
for i,k in enumerate(range(1,5)): for i,k in enumerate(range(1,5)):
print i, k print i, k
#T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") #T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def go_c_enumerate(): def go_c_enumerate():
"""
>>> go_c_enumerate()
0 1
1 2
2 3
3 4
"""
cdef int i,k cdef int i,k
for i,k in enumerate(range(1,5)): for i,k in enumerate(range(1,5)):
print i, k print i, k
#T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") #T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def go_c_enumerate_step(): def go_c_enumerate_step():
"""
>>> go_c_enumerate_step()
0 1
1 3
2 5
"""
cdef int i,k cdef int i,k
for i,k in enumerate(range(1,7,2)): for i,k in enumerate(range(1,7,2)):
print i, k print i, k
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def py_enumerate_dict(dict d): def py_enumerate_dict(dict d):
"""
>>> py_enumerate_dict({})
:: 55 99
>>> py_enumerate_dict(dict(a=1, b=2, c=3))
0 a
1 c
2 b
:: 2 b
"""
cdef int i = 55 cdef int i = 55
k = 99 k = 99
for i,k in enumerate(d): for i,k in enumerate(d):
...@@ -92,6 +56,11 @@ def py_enumerate_dict(dict d): ...@@ -92,6 +56,11 @@ def py_enumerate_dict(dict d):
@cython.test_fail_if_path_exists("//SimpleCallNode") @cython.test_fail_if_path_exists("//SimpleCallNode")
def py_enumerate_break(*t): def py_enumerate_break(*t):
"""
>>> py_enumerate_break(1,2,3,4)
0 1
:: 0 1
"""
i,k = 55,99 i,k = 55,99
for i,k in enumerate(t): for i,k in enumerate(t):
print i, k print i, k
...@@ -100,6 +69,12 @@ def py_enumerate_break(*t): ...@@ -100,6 +69,12 @@ def py_enumerate_break(*t):
@cython.test_fail_if_path_exists("//SimpleCallNode") @cython.test_fail_if_path_exists("//SimpleCallNode")
def py_enumerate_return(*t): def py_enumerate_return(*t):
"""
>>> py_enumerate_return()
:: 55 99
>>> py_enumerate_return(1,2,3,4)
0 1
"""
i,k = 55,99 i,k = 55,99
for i,k in enumerate(t): for i,k in enumerate(t):
print i, k print i, k
...@@ -108,6 +83,14 @@ def py_enumerate_return(*t): ...@@ -108,6 +83,14 @@ def py_enumerate_return(*t):
@cython.test_fail_if_path_exists("//SimpleCallNode") @cython.test_fail_if_path_exists("//SimpleCallNode")
def py_enumerate_continue(*t): def py_enumerate_continue(*t):
"""
>>> py_enumerate_continue(1,2,3,4)
0 1
1 2
2 3
3 4
:: 3 4
"""
i,k = 55,99 i,k = 55,99
for i,k in enumerate(t): for i,k in enumerate(t):
print i, k print i, k
...@@ -116,6 +99,10 @@ def py_enumerate_continue(*t): ...@@ -116,6 +99,10 @@ def py_enumerate_continue(*t):
# T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") # T442 @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def empty_c_enumerate(): def empty_c_enumerate():
"""
>>> empty_c_enumerate()
(55, 99)
"""
cdef int i = 55, k = 99 cdef int i = 55, k = 99
for i,k in enumerate(range(0)): for i,k in enumerate(range(0)):
print i, k print i, k
...@@ -123,16 +110,37 @@ def empty_c_enumerate(): ...@@ -123,16 +110,37 @@ def empty_c_enumerate():
# not currently optimised # not currently optimised
def single_target_enumerate(): def single_target_enumerate():
"""
>>> single_target_enumerate()
0 1
1 2
2 3
3 4
"""
for t in enumerate(range(1,5)): for t in enumerate(range(1,5)):
print t[0], t[1] print t[0], t[1]
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']")
def multi_enumerate(): def multi_enumerate():
"""
>>> multi_enumerate()
0 0 0 1
1 1 1 2
2 2 2 3
3 3 3 4
"""
for a,(b,(c,d)) in enumerate(enumerate(enumerate(range(1,5)))): for a,(b,(c,d)) in enumerate(enumerate(enumerate(range(1,5)))):
print a,b,c,d print a,b,c,d
# T442 @cython.test_fail_if_path_exists("//SimpleCallNode") # T442 @cython.test_fail_if_path_exists("//SimpleCallNode")
def multi_c_enumerate(): def multi_c_enumerate():
"""
>>> multi_c_enumerate()
0 0 0 1
1 1 1 2
2 2 2 3
3 3 3 4
"""
cdef int a,b,c,d cdef int a,b,c,d
for a,(b,(c,d)) in enumerate(enumerate(enumerate(range(1,5)))): for a,(b,(c,d)) in enumerate(enumerate(enumerate(range(1,5)))):
print a,b,c,d print a,b,c,d
......
__doc__ = u"""
>>> foo(0)
>>> foo(1)
Traceback (most recent call last):
RuntimeError
"""
cdef int CHKERR(int ierr) except -1: cdef int CHKERR(int ierr) except -1:
if ierr==0: return 0 if ierr==0: return 0
raise RuntimeError raise RuntimeError
...@@ -13,6 +6,12 @@ cdef int obj2int(object ob) except *: ...@@ -13,6 +6,12 @@ cdef int obj2int(object ob) except *:
return ob return ob
def foo(a): def foo(a):
"""
>>> foo(0)
>>> foo(1)
Traceback (most recent call last):
RuntimeError
"""
cdef int i = obj2int(a) cdef int i = obj2int(a)
CHKERR(i) CHKERR(i)
......
__doc__ = u"""
>>> set_attr(5)
>>> get_attr()
"""
cdef class MyExt: cdef class MyExt:
cdef object attr cdef object attr
def set_attr(value): def set_attr(value):
"""
>>> set_attr(5)
"""
MyExt().attr = value MyExt().attr = value
def get_attr(): def get_attr():
"""
>>> get_attr()
"""
return MyExt().attr return MyExt().attr
__doc__ = u"""
>>> test()
5
0
20
5
"""
cdef class Spam: cdef class Spam:
cdef int tons cdef int tons
...@@ -25,6 +17,13 @@ cdef class SuperSpam(Spam): ...@@ -25,6 +17,13 @@ cdef class SuperSpam(Spam):
self.tons = self.tons + 2 * x self.tons = self.tons + 2 * x
def test(): def test():
"""
>>> test()
5
0
20
5
"""
cdef Spam s cdef Spam s
cdef SuperSpam ss cdef SuperSpam ss
s = Spam() s = Spam()
......
__doc__ = u""" __doc__ = u"""
>>> class FakeSeq(object): >>> class FakeSeq(object):
... def __init__(self, length): ... def __init__(self, length):
... self._values = list(range(1,length+1)) ... self._values = list(range(1,length+1))
... def __getitem__(self, i): ... def __getitem__(self, i):
... return self._values[i] ... return self._values[i]
>>> unpack([1,2]) >>> unpack( FakeSeq(2) )
(1, 2) (1, 2)
>>> unpack_list([1,2]) >>> unpack_recursive( FakeSeq(4) )
(1, 2) (1, [2, 3], 4)
>>> unpack_tuple((1,2))
(1, 2)
>>> unpack( FakeSeq(2) )
(1, 2)
>>> unpack('12')
('1', '2')
>>> unpack_into_list('123')
('1', ['2'], '3')
>>> unpack_into_tuple('123')
('1', ['2'], '3')
>>> unpack_in_loop([(1,2), (1,2,3), (1,2,3,4)])
1
([1], 2)
([1, 2], 3)
([1, 2, 3], 4)
2
(1, [2])
(1, [2, 3])
(1, [2, 3, 4])
3
(1, [], 2)
(1, [2], 3)
(1, [2, 3], 4)
>>> unpack_recursive((1,2,3,4))
(1, [2, 3], 4)
>>> unpack_recursive( FakeSeq(4) )
(1, [2, 3], 4)
>>> unpack_typed((1,2))
([1], 2)
>>> assign()
(1, [2, 3, 4], 5)
>>> unpack_right('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right('1')
('1', [])
>>> unpack_right([1])
(1, [])
>>> unpack_right('12')
('1', ['2'])
>>> unpack_right([1,2])
(1, [2])
>>> unpack_right('123')
('1', ['2', '3'])
>>> unpack_right([1,2,3])
(1, [2, 3])
>>> unpack_right_list([1])
(1, [])
>>> unpack_right_list([1,2])
(1, [2])
>>> unpack_right_list([1,2,3])
(1, [2, 3])
>>> unpack_right_tuple((1,))
(1, [])
>>> unpack_right_tuple((1,2))
(1, [2])
>>> unpack_right_tuple((1,2,3))
(1, [2, 3])
>>> unpack_left('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left('1')
([], '1')
>>> unpack_left([1])
([], 1)
>>> unpack_left('12')
(['1'], '2')
>>> unpack_left([1,2])
([1], 2)
>>> unpack_left('123')
(['1', '2'], '3')
>>> unpack_left([1,2,3])
([1, 2], 3)
>>> unpack_left_list([1])
([], 1)
>>> unpack_left_list([1,2])
([1], 2)
>>> unpack_left_list([1,2,3])
([1, 2], 3)
>>> unpack_left_tuple((1,))
([], 1)
>>> unpack_left_tuple((1,2))
([1], 2)
>>> unpack_left_tuple((1,2,3))
([1, 2], 3)
>>> unpack_middle('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle('1')
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle([1])
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle_list([1])
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle_tuple((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle('12')
('1', [], '2')
>>> unpack_middle([1,2])
(1, [], 2)
>>> unpack_middle('123')
('1', ['2'], '3')
>>> unpack_middle([1,2,3])
(1, [2], 3)
>>> unpack_middle_list([1,2])
(1, [], 2)
>>> unpack_middle_list([1,2,3])
(1, [2], 3)
>>> unpack_middle_tuple((1,2))
(1, [], 2)
>>> unpack_middle_tuple((1,2,3))
(1, [2], 3)
>>> a,b,c = unpack_middle(list(range(100)))
>>> a, len(b), c
(0, 98, 99)
>>> a,b,c = unpack_middle_list(list(range(100)))
>>> a, len(b), c
(0, 98, 99)
>>> a,b,c = unpack_middle_tuple(tuple(range(100)))
>>> a, len(b), c
(0, 98, 99)
""" """
def unpack(l): def unpack(l):
"""
>>> unpack([1,2])
(1, 2)
>>> unpack('12')
('1', '2')
"""
a, b = l a, b = l
return a,b return a,b
def unpack_list(list l): def unpack_list(list l):
"""
>>> unpack_list([1,2])
(1, 2)
"""
a, b = l a, b = l
return a,b return a,b
def unpack_tuple(tuple t): def unpack_tuple(tuple t):
"""
>>> unpack_tuple((1,2))
(1, 2)
"""
a, b = t a, b = t
return a,b return a,b
def assign(): def assign():
"""
>>> assign()
(1, [2, 3, 4], 5)
"""
*a, b = 1,2,3,4,5 *a, b = 1,2,3,4,5
assert a+[b] == [1,2,3,4,5], (a,b) assert a+[b] == [1,2,3,4,5], (a,b)
a, *b = 1,2,3,4,5 a, *b = 1,2,3,4,5
...@@ -198,6 +50,10 @@ def assign(): ...@@ -198,6 +50,10 @@ def assign():
return a,b,c return a,b,c
def unpack_into_list(l): def unpack_into_list(l):
"""
>>> unpack_into_list('123')
('1', ['2'], '3')
"""
[*a, b] = l [*a, b] = l
assert a+[b] == list(l), repr((a+[b],list(l))) assert a+[b] == list(l), repr((a+[b],list(l)))
[a, *b] = l [a, *b] = l
...@@ -206,6 +62,10 @@ def unpack_into_list(l): ...@@ -206,6 +62,10 @@ def unpack_into_list(l):
return a,b,c return a,b,c
def unpack_into_tuple(t): def unpack_into_tuple(t):
"""
>>> unpack_into_tuple('123')
('1', ['2'], '3')
"""
(*a, b) = t (*a, b) = t
assert a+[b] == list(t), repr((a+[b],list(t))) assert a+[b] == list(t), repr((a+[b],list(t)))
(a, *b) = t (a, *b) = t
...@@ -214,6 +74,21 @@ def unpack_into_tuple(t): ...@@ -214,6 +74,21 @@ def unpack_into_tuple(t):
return a,b,c return a,b,c
def unpack_in_loop(list_of_sequences): def unpack_in_loop(list_of_sequences):
"""
>>> unpack_in_loop([(1,2), (1,2,3), (1,2,3,4)])
1
([1], 2)
([1, 2], 3)
([1, 2, 3], 4)
2
(1, [2])
(1, [2, 3])
(1, [2, 3, 4])
3
(1, [], 2)
(1, [2], 3)
(1, [2, 3], 4)
"""
print 1 print 1
for *a,b in list_of_sequences: for *a,b in list_of_sequences:
print((a,b)) print((a,b))
...@@ -225,49 +100,193 @@ def unpack_in_loop(list_of_sequences): ...@@ -225,49 +100,193 @@ def unpack_in_loop(list_of_sequences):
print((a,b,c)) print((a,b,c))
def unpack_recursive(t): def unpack_recursive(t):
"""
>>> unpack_recursive((1,2,3,4))
(1, [2, 3], 4)
"""
*(a, *b), c = t *(a, *b), c = t
return a,b,c return a,b,c
def unpack_typed(t): def unpack_typed(t):
"""
>>> unpack_typed((1,2))
([1], 2)
"""
cdef list a cdef list a
*a, b = t *a, b = t
return a,b return a,b
def unpack_right(l): def unpack_right(l):
"""
>>> unpack_right('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right('1')
('1', [])
>>> unpack_right([1])
(1, [])
>>> unpack_right('12')
('1', ['2'])
>>> unpack_right([1,2])
(1, [2])
>>> unpack_right('123')
('1', ['2', '3'])
>>> unpack_right([1,2,3])
(1, [2, 3])
"""
a, *b = l a, *b = l
return a,b return a,b
def unpack_right_list(list l): def unpack_right_list(list l):
"""
>>> unpack_right_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right_list([1])
(1, [])
>>> unpack_right_list([1,2])
(1, [2])
>>> unpack_right_list([1,2,3])
(1, [2, 3])
"""
a, *b = l a, *b = l
return a,b return a,b
def unpack_right_tuple(tuple t): def unpack_right_tuple(tuple t):
"""
>>> unpack_right_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_right_tuple((1,))
(1, [])
>>> unpack_right_tuple((1,2))
(1, [2])
>>> unpack_right_tuple((1,2,3))
(1, [2, 3])
"""
a, *b = t a, *b = t
return a,b return a,b
def unpack_left(l): def unpack_left(l):
"""
>>> unpack_left('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left('1')
([], '1')
>>> unpack_left([1])
([], 1)
>>> unpack_left('12')
(['1'], '2')
>>> unpack_left([1,2])
([1], 2)
>>> unpack_left('123')
(['1', '2'], '3')
>>> unpack_left([1,2,3])
([1, 2], 3)
"""
*a, b = l *a, b = l
return a,b return a,b
def unpack_left_list(list l): def unpack_left_list(list l):
"""
>>> unpack_left_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left_list([1])
([], 1)
>>> unpack_left_list([1,2])
([1], 2)
>>> unpack_left_list([1,2,3])
([1, 2], 3)
"""
*a, b = l *a, b = l
return a,b return a,b
def unpack_left_tuple(tuple t): def unpack_left_tuple(tuple t):
"""
>>> unpack_left_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_left_tuple((1,))
([], 1)
>>> unpack_left_tuple((1,2))
([1], 2)
>>> unpack_left_tuple((1,2,3))
([1, 2], 3)
"""
*a, b = t *a, b = t
return a,b return a,b
def unpack_middle(l): def unpack_middle(l):
"""
>>> unpack_middle('')
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle('1')
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle([1])
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle('12')
('1', [], '2')
>>> unpack_middle([1,2])
(1, [], 2)
>>> unpack_middle('123')
('1', ['2'], '3')
>>> unpack_middle([1,2,3])
(1, [2], 3)
"""
a, *b, c = l a, *b, c = l
return a,b,c return a,b,c
def unpack_middle_list(list l): def unpack_middle_list(list l):
"""
>>> unpack_middle_list([])
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle_list([1])
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle_list([1,2])
(1, [], 2)
>>> unpack_middle_list([1,2,3])
(1, [2], 3)
"""
a, *b, c = l a, *b, c = l
return a,b,c return a,b,c
def unpack_middle_tuple(tuple t): def unpack_middle_tuple(tuple t):
"""
>>> unpack_middle_tuple(())
Traceback (most recent call last):
ValueError: need more than 0 values to unpack
>>> unpack_middle_tuple((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> unpack_middle_tuple((1,2))
(1, [], 2)
>>> unpack_middle_tuple((1,2,3))
(1, [2], 3)
>>> a,b,c = unpack_middle(list(range(100)))
>>> a, len(b), c
(0, 98, 99)
>>> a,b,c = unpack_middle_list(list(range(100)))
>>> a, len(b), c
(0, 98, 99)
>>> a,b,c = unpack_middle_tuple(tuple(range(100)))
>>> a, len(b), c
(0, 98, 99)
"""
a, *b, c = t a, *b, c = t
return a,b,c return a,b,c
def simple(): def simple():
""" """
>>> simple() >>> simple()
......
__doc__ = u"""
>>> p = create()
>>> rest(p)
0
"""
cdef class Parrot: cdef class Parrot:
cdef object name cdef object name
cdef int alive cdef int alive
...@@ -18,6 +12,11 @@ def create(): ...@@ -18,6 +12,11 @@ def create():
return p return p
def rest(Norwegian polly): def rest(Norwegian polly):
"""
>>> p = create()
>>> rest(p)
0
"""
cdef Parrot fred cdef Parrot fred
cdef object spam cdef object spam
spam = None spam = None
......
...@@ -2,27 +2,46 @@ __doc__ = u""" ...@@ -2,27 +2,46 @@ __doc__ = u"""
>>> ext = Ext() >>> ext = Ext()
>>> b,c,d,e,f,g,h,k = ext.b,ext.c,ext.d,ext.e,ext.f,ext.g,ext.h,ext.k >>> b,c,d,e,f,g,h,k = ext.b,ext.c,ext.d,ext.e,ext.f,ext.g,ext.h,ext.k
>>> b(1,2,3) """
>>> b(1,2,3,4)
Traceback (most recent call last): cdef class Ext:
TypeError: b() takes exactly 3 positional arguments (4 given) def b(self, a, b, c):
pass
def c(self, a, b, c=1):
pass
def d(self, a, b, *, c = 88):
pass
def e(self, a, b, c = 88, **kwds):
pass
def f(self, a, b, *, c, d = 42):
pass
def g(self, a, b, *, c, d = 42, e = 17, f, **kwds):
pass
def h(self, a, b, *args, c, d = 42, e = 17, f, **kwds):
pass
def k(self, a, b, c=1, *args, d = 42, e = 17, f, **kwds):
pass
"""# c
>>> c(1,2) >>> c(1,2)
>>> c(1,2,3) >>> c(1,2,3)
>>> c(1,2,3,4) >>> c(1,2,3,4)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: c() takes at most 3 positional arguments (4 given) TypeError: c() takes at most 3 positional arguments (4 given)
>>> d(1,2) # b
>>> d(1,2, c=1) >>> b(1,2,3)
>>> b(1,2,3,4)
>>> d(1,2,3)
Traceback (most recent call last):
TypeError: d() takes exactly 2 positional arguments (3 given)
>>> d(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: d() got an unexpected keyword argument 'd' TypeError: b() takes exactly 3 positional arguments (4 given)
# e
>>> e(1,2) >>> e(1,2)
>>> e(1,2, c=1) >>> e(1,2, c=1)
>>> e(1,2, d=1) >>> e(1,2, d=1)
...@@ -32,19 +51,18 @@ __doc__ = u""" ...@@ -32,19 +51,18 @@ __doc__ = u"""
Traceback (most recent call last): Traceback (most recent call last):
TypeError: e() takes at most 3 positional arguments (4 given) TypeError: e() takes at most 3 positional arguments (4 given)
>>> f(1,2, c=1) # d
>>> f(1,2, c=1, d=2) >>> d(1,2)
>>> d(1,2, c=1)
>>> f(1,2,3) >>> d(1,2,3)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (3 given)
>>> f(1,2)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: f() needs keyword-only argument c TypeError: d() takes exactly 2 positional arguments (3 given)
>>> f(1,2, c=1, e=2) >>> d(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'e' TypeError: d() got an unexpected keyword argument 'd'
# g
>>> g(1,2, c=1, f=2) >>> g(1,2, c=1, f=2)
>>> g(1,2, c=1, e=0, f=2, d=11) >>> g(1,2, c=1, e=0, f=2, d=11)
>>> g(1,2, c=1, f=2, e=0, x=25) >>> g(1,2, c=1, f=2, e=0, x=25)
...@@ -59,6 +77,21 @@ __doc__ = u""" ...@@ -59,6 +77,21 @@ __doc__ = u"""
Traceback (most recent call last): Traceback (most recent call last):
TypeError: g() needs keyword-only argument f TypeError: g() needs keyword-only argument f
# f
>>> f(1,2, c=1)
>>> f(1,2, c=1, d=2)
>>> f(1,2,3)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (3 given)
>>> f(1,2)
Traceback (most recent call last):
TypeError: f() needs keyword-only argument c
>>> f(1,2, c=1, e=2)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'e'
# h
>>> h(1,2, c=1, f=2) >>> h(1,2, c=1, f=2)
>>> h(1,2, c=1, f=2, e=3) >>> h(1,2, c=1, f=2, e=3)
>>> h(1,2,3,4,5,6, c=1, f=2) >>> h(1,2,3,4,5,6, c=1, f=2)
...@@ -71,6 +104,7 @@ __doc__ = u""" ...@@ -71,6 +104,7 @@ __doc__ = u"""
Traceback (most recent call last): Traceback (most recent call last):
TypeError: h() needs keyword-only argument c TypeError: h() needs keyword-only argument c
# k
>>> k(1,2, c=1, f=2) >>> k(1,2, c=1, f=2)
>>> k(1,2, c=1, f=2, e=3) >>> k(1,2, c=1, f=2, e=3)
>>> k(1,2,3,4,5,6, d=1, f=2) >>> k(1,2,3,4,5,6, d=1, f=2)
...@@ -83,28 +117,3 @@ __doc__ = u""" ...@@ -83,28 +117,3 @@ __doc__ = u"""
Traceback (most recent call last): Traceback (most recent call last):
TypeError: k() needs keyword-only argument f TypeError: k() needs keyword-only argument f
""" """
cdef class Ext:
def b(self, a, b, c):
pass
def c(self, a, b, c=1):
pass
def d(self, a, b, *, c = 88):
pass
def e(self, a, b, c = 88, **kwds):
pass
def f(self, a, b, *, c, d = 42):
pass
def g(self, a, b, *, c, d = 42, e = 17, f, **kwds):
pass
def h(self, a, b, *args, c, d = 42, e = 17, f, **kwds):
pass
def k(self, a, b, c=1, *args, d = 42, e = 17, f, **kwds):
pass
...@@ -7,4 +7,3 @@ cdef class Spam: ...@@ -7,4 +7,3 @@ cdef class Spam:
def __len__(self): def __len__(self):
return 0 return 0
__doc__ = u"""
>>> tomato()
42
"""
cdef class Spam: cdef class Spam:
property eggs: property eggs:
...@@ -11,6 +6,10 @@ cdef class Spam: ...@@ -11,6 +6,10 @@ cdef class Spam:
return 42 return 42
def tomato(): def tomato():
"""
>>> tomato()
42
"""
cdef Spam spam cdef Spam spam
cdef object lettuce cdef object lettuce
spam = Spam() spam = Spam()
......
__doc__ = u"""
>>> s = Spam(12)
>>> s.eat()
12 42
>>> f(s)
Traceback (most recent call last):
AttributeError: 'exttype.Spam' object has no attribute 'foo'
>>> s.eat()
12 42
>>> class Spam2(Spam):
... foo = 1
>>> s = Spam2(12)
>>> s.eat()
12 42
>>> f(s)
>>> s.eat()
12 42
"""
cdef gobble(a, b): cdef gobble(a, b):
print a, b print a, b
cdef class Spam: cdef class Spam:
"""
>>> s = Spam(12)
>>> s.eat()
12 42
"""
cdef eggs cdef eggs
cdef int ham cdef int ham
...@@ -37,6 +22,22 @@ cdef class Spam: ...@@ -37,6 +22,22 @@ cdef class Spam:
gobble(self.eggs, self.ham) gobble(self.eggs, self.ham)
def f(Spam spam): def f(Spam spam):
"""
>>> s = Spam(12)
>>> f(s)
Traceback (most recent call last):
AttributeError: 'exttype.Spam' object has no attribute 'foo'
>>> s.eat()
12 42
>>> class Spam2(Spam):
... foo = 1
>>> s = Spam2(12)
>>> s.eat()
12 42
>>> f(s)
>>> s.eat()
12 42
"""
x = spam.eggs x = spam.eggs
y = spam.ham y = spam.ham
z = spam.foo z = spam.foo
......
...@@ -8,4 +8,3 @@ ftang ...@@ -8,4 +8,3 @@ ftang
include "filenames.pxi" include "filenames.pxi"
foo = 42 foo = 42
__doc__ = u"""
>>> test_in('ABC')
1
>>> test_in('abc')
2
>>> test_in('X')
3
>>> test_in('XYZ')
4
>>> test_in('ABCXYZ')
5
>>> test_in('')
5
>>> test_not_in('abc')
1
>>> test_not_in('CDE')
2
>>> test_not_in('CDEF')
3
>>> test_not_in('BCD')
4
"""
def test_in(s): def test_in(s):
"""
>>> test_in('ABC')
1
>>> test_in('abc')
2
>>> test_in('X')
3
>>> test_in('XYZ')
4
>>> test_in('ABCXYZ')
5
>>> test_in('')
5
"""
if s in (u'ABC', u'BCD'): if s in (u'ABC', u'BCD'):
return 1 return 1
elif s.upper() in (u'ABC', u'BCD'): elif s.upper() in (u'ABC', u'BCD'):
...@@ -35,6 +25,16 @@ def test_in(s): ...@@ -35,6 +25,16 @@ def test_in(s):
return 5 return 5
def test_not_in(s): def test_not_in(s):
"""
>>> test_not_in('abc')
1
>>> test_not_in('CDE')
2
>>> test_not_in('CDEF')
3
>>> test_not_in('BCD')
4
"""
if s not in (u'ABC', u'BCD', u'CDE', u'CDEF'): if s not in (u'ABC', u'BCD', u'CDE', u'CDEF'):
return 1 return 1
elif s.upper() not in (u'ABC', u'BCD', u'CDEF'): elif s.upper() not in (u'ABC', u'BCD', u'CDEF'):
......
__doc__ = u""" def floor_div_float(double a, double b):
"""
>>> floor_div_float(2, 1.5) >>> floor_div_float(2, 1.5)
1.0 1.0
>>> floor_div_float(2, -1.5) >>> floor_div_float(2, -1.5)
...@@ -7,7 +8,5 @@ __doc__ = u""" ...@@ -7,7 +8,5 @@ __doc__ = u"""
-2.0 -2.0
>>> floor_div_float(1e10, 1e-10) >>> floor_div_float(1e10, 1e-10)
1e+20 1e+20
""" """
def floor_div_float(double a, double b):
return a // b return a // b
__doc__ = u""" def fmod(double a, double b):
"""
>>> fmod(7, 1.25) >>> fmod(7, 1.25)
0.75 0.75
""" """
def fmod(double a, double b):
return a % b return a % b
__doc__ = u""" def double_target(a, b):
"""
>>> double_target(0, 4) >>> double_target(0, 4)
at 0.0 at 0.0
at 1.0 at 1.0
at 2.0 at 2.0
at 3.0 at 3.0
4.0 4.0
>>> double_step(0, 2, .5) """
at 0.0
at 0.5
at 1.0
at 1.5
2.0
>>> double_step_typed(0, 2, .5)
at 0.0
at 0.5
at 1.0
at 1.5
2.0
>>> double_step_py_target(0, 2, .5)
at 0.0
at 0.5
at 1.0
at 1.5
2.0
>>> int_step_py_target(0, 2, 1)
at 0
at 1
2
"""
def double_target(a, b):
cdef double x cdef double x
for x from a <= x < b: for x from a <= x < b:
print u"at", x print u"at", x
return x return x
def double_step(a, b, dx): def double_step(a, b, dx):
"""
>>> double_step(0, 2, .5)
at 0.0
at 0.5
at 1.0
at 1.5
2.0
"""
cdef double x cdef double x
for x from a <= x < b by dx: for x from a <= x < b by dx:
print u"at", x print u"at", x
return x return x
def double_step_typed(a, b, double dx): def double_step_typed(a, b, double dx):
"""
>>> double_step_typed(0, 2, .5)
at 0.0
at 0.5
at 1.0
at 1.5
2.0
"""
cdef double x cdef double x
for x from a <= x < b by dx: for x from a <= x < b by dx:
print u"at", x print u"at", x
return x return x
def double_step_py_target(a, b, double dx): def double_step_py_target(a, b, double dx):
"""
>>> double_step_py_target(0, 2, .5)
at 0.0
at 0.5
at 1.0
at 1.5
2.0
"""
cdef object x cdef object x
for x from a <= x < b by dx: for x from a <= x < b by dx:
print u"at", x print u"at", x
return x return x
def int_step_py_target(a, b, int dx): def int_step_py_target(a, b, int dx):
"""
>>> int_step_py_target(0, 2, 1)
at 0
at 1
2
"""
cdef object x cdef object x
for x from a <= x < b by dx: for x from a <= x < b by dx:
print u"at", x print u"at", x
......
__doc__ = u"""
>>> test_modify()
0
1
2
3
4
<BLANKLINE>
(4, 0)
>>> test_fix()
0
1
2
3
4
<BLANKLINE>
4
>>> test_break()
0
1
2
<BLANKLINE>
(2, 0)
>>> test_return()
0
1
2
(2, 0)
"""
cimport cython cimport cython
@cython.test_assert_path_exists("//ForFromStatNode") @cython.test_assert_path_exists("//ForFromStatNode")
@cython.test_fail_if_path_exists("//ForInStatNode") @cython.test_fail_if_path_exists("//ForInStatNode")
def test_modify(): def test_modify():
"""
>>> test_modify()
0
1
2
3
4
<BLANKLINE>
(4, 0)
"""
cdef int i, n = 5 cdef int i, n = 5
for i in range(n): for i in range(n):
print i print i
...@@ -43,6 +23,16 @@ def test_modify(): ...@@ -43,6 +23,16 @@ def test_modify():
@cython.test_assert_path_exists("//ForFromStatNode") @cython.test_assert_path_exists("//ForFromStatNode")
@cython.test_fail_if_path_exists("//ForInStatNode") @cython.test_fail_if_path_exists("//ForInStatNode")
def test_fix(): def test_fix():
"""
>>> test_fix()
0
1
2
3
4
<BLANKLINE>
4
"""
cdef int i cdef int i
for i in range(5): for i in range(5):
print i print i
...@@ -52,6 +42,14 @@ def test_fix(): ...@@ -52,6 +42,14 @@ def test_fix():
@cython.test_assert_path_exists("//ForFromStatNode") @cython.test_assert_path_exists("//ForFromStatNode")
@cython.test_fail_if_path_exists("//ForInStatNode") @cython.test_fail_if_path_exists("//ForInStatNode")
def test_break(): def test_break():
"""
>>> test_break()
0
1
2
<BLANKLINE>
(2, 0)
"""
cdef int i, n = 5 cdef int i, n = 5
for i in range(n): for i in range(n):
print i print i
...@@ -66,6 +64,13 @@ def test_break(): ...@@ -66,6 +64,13 @@ def test_break():
@cython.test_assert_path_exists("//ForFromStatNode") @cython.test_assert_path_exists("//ForFromStatNode")
@cython.test_fail_if_path_exists("//ForInStatNode") @cython.test_fail_if_path_exists("//ForInStatNode")
def test_return(): def test_return():
"""
>>> test_return()
0
1
2
(2, 0)
"""
cdef int i, n = 5 cdef int i, n = 5
for i in range(n): for i in range(n):
print i print i
......
__doc__ = u"""
>>> for_else()
30
>>> print( u'*'.join(int_comp()) )
00*01*02
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '").replace(u' u"', u' "') __doc__ = __doc__.replace(u" u'", u" '").replace(u' u"', u' "')
def for_else(): def for_else():
"""
>>> for_else()
30
>>> print( u'*'.join(int_comp()) )
00*01*02
"""
cdef int i, j=0, k=2 cdef int i, j=0, k=2
for i from 0 <= i < 10: for i from 0 <= i < 10:
j += k j += k
......
import sys import sys
def reraise(f, exc): def reraise(f, exc):
......
...@@ -11,8 +11,6 @@ __doc__ = u""" ...@@ -11,8 +11,6 @@ __doc__ = u"""
... ...
TypeError: That's kind of a round number... TypeError: That's kind of a round number...
>>> __hash__(-1)
-1
""" """
cdef class A: cdef class A:
...@@ -26,4 +24,8 @@ cdef class A: ...@@ -26,4 +24,8 @@ cdef class A:
return self.a return self.a
cpdef long __hash__(long x): cpdef long __hash__(long x):
"""
>>> __hash__(-1)
-1
"""
return x return x
__doc__ = u""" def f(a, b):
"""
>>> f(0,0) >>> f(0,0)
0 0
>>> f(1,2) >>> f(1,2)
2 2
>>> f(1,-1) >>> f(1,-1)
1 1
"""
>>> g(1,2)
1
>>> g(0,2)
2
>>> g(0,0)
0
>>> h(1,2)
1
>>> h(0,2)
2
>>> h(0,0)
3
>>> i(1,2)
1
>>> i(2,2)
2
>>> i(2,1)
0
"""
def f(a, b):
x = 0 x = 0
if a: if a:
x = 1 x = 1
...@@ -37,6 +15,14 @@ def f(a, b): ...@@ -37,6 +15,14 @@ def f(a, b):
return x return x
def g(a, b): def g(a, b):
"""
>>> g(1,2)
1
>>> g(0,2)
2
>>> g(0,0)
0
"""
x = 0 x = 0
if a: if a:
x = 1 x = 1
...@@ -45,6 +31,14 @@ def g(a, b): ...@@ -45,6 +31,14 @@ def g(a, b):
return x return x
def h(a, b): def h(a, b):
"""
>>> h(1,2)
1
>>> h(0,2)
2
>>> h(0,0)
3
"""
x = 0 x = 0
if a: if a:
x = 1 x = 1
...@@ -60,6 +54,14 @@ except ImportError: ...@@ -60,6 +54,14 @@ except ImportError:
import builtins import builtins
def i(a, b): def i(a, b):
"""
>>> i(1,2)
1
>>> i(2,2)
2
>>> i(2,1)
0
"""
x = 0 x = 0
if builtins.str(a).upper() == u"1": if builtins.str(a).upper() == u"1":
x = 1 x = 1
......
__doc__ = u""" from distutils import cmd, core, version
>>> from distutils import cmd, core, version
>>> import1() == (cmd, core, version)
True
>>> import2() == (cmd, core, version)
True
>>> import3() == (cmd, core, version)
True
>>> import4() == (cmd, core, version)
True
>>> typed_imports()
True
True
an integer is required
Expected type, got int
"""
def import1(): def import1():
"""
>>> import1() == (cmd, core, version)
True
"""
from distutils import ( from distutils import (
cmd, cmd,
...@@ -25,6 +14,10 @@ core, version) ...@@ -25,6 +14,10 @@ core, version)
def import2(): def import2():
"""
>>> import2() == (cmd, core, version)
True
"""
from distutils import (cmd, from distutils import (cmd,
core, core,
...@@ -36,16 +29,31 @@ core, ...@@ -36,16 +29,31 @@ core,
def import3(): def import3():
"""
>>> import3() == (cmd, core, version)
True
"""
from distutils import (cmd, core,version) from distutils import (cmd, core,version)
return cmd, core, version return cmd, core, version
def import4(): def import4():
"""
>>> import4() == (cmd, core, version)
True
"""
from distutils import cmd, core, version from distutils import cmd, core, version
return cmd, core, version return cmd, core, version
def typed_imports(): def typed_imports():
"""
>>> typed_imports()
True
True
an integer is required
Expected type, got int
"""
import sys import sys
import types import types
...@@ -66,4 +74,3 @@ def typed_imports(): ...@@ -66,4 +74,3 @@ def typed_imports():
from sys import maxunicode as t from sys import maxunicode as t
except TypeError, e: except TypeError, e:
print e print e
__doc__ = u"""
>>> index_tuple((1,1,2,3,5), 0)
1
>>> index_tuple((1,1,2,3,5), 3)
3
>>> index_tuple((1,1,2,3,5), -1)
5
>>> index_tuple((1,1,2,3,5), 100)
Traceback (most recent call last):
...
IndexError: tuple index out of range
>>> index_list([2,3,5,7,11,13,17,19], 0)
2
>>> index_list([2,3,5,7,11,13,17,19], 5)
13
>>> index_list([2,3,5,7,11,13,17,19], -1)
19
>>> index_list([2,3,5,7,11,13,17,19], 100)
Traceback (most recent call last):
...
IndexError: list index out of range
>>> index_object([2,3,5,7,11,13,17,19], 1)
3
>>> index_object([2,3,5,7,11,13,17,19], -1)
19
>>> index_object((1,1,2,3,5), 2)
2
>>> index_object((1,1,2,3,5), -2)
3
>>> index_object("abcdef...z", 0)
'a'
>>> index_object("abcdef...z", -1)
'z'
>>> index_object("abcdef...z", 100)
Traceback (most recent call last):
...
IndexError: string index out of range
>>> index_object(100, 100)
Traceback (most recent call last):
...
TypeError: 'int' object is unsubscriptable
>>> test_unsigned_long()
>>> test_unsigned_short()
>>> test_long_long()
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u'is unsubscriptable', u'is not subscriptable') __doc__ = __doc__.replace(u'is unsubscriptable', u'is not subscriptable')
...@@ -55,18 +5,67 @@ elif sys.version_info < (2,5): ...@@ -55,18 +5,67 @@ elif sys.version_info < (2,5):
__doc__ = __doc__.replace(u"'int' object is unsubscriptable", u'unsubscriptable object') __doc__ = __doc__.replace(u"'int' object is unsubscriptable", u'unsubscriptable object')
def index_tuple(tuple t, int i): def index_tuple(tuple t, int i):
"""
>>> index_tuple((1,1,2,3,5), 0)
1
>>> index_tuple((1,1,2,3,5), 3)
3
>>> index_tuple((1,1,2,3,5), -1)
5
>>> index_tuple((1,1,2,3,5), 100)
Traceback (most recent call last):
...
IndexError: tuple index out of range
"""
return t[i] return t[i]
def index_list(list L, int i): def index_list(list L, int i):
"""
>>> index_list([2,3,5,7,11,13,17,19], 0)
2
>>> index_list([2,3,5,7,11,13,17,19], 5)
13
>>> index_list([2,3,5,7,11,13,17,19], -1)
19
>>> index_list([2,3,5,7,11,13,17,19], 100)
Traceback (most recent call last):
...
IndexError: list index out of range
"""
return L[i] return L[i]
def index_object(object o, int i): def index_object(object o, int i):
"""
>>> index_object([2,3,5,7,11,13,17,19], 1)
3
>>> index_object([2,3,5,7,11,13,17,19], -1)
19
>>> index_object((1,1,2,3,5), 2)
2
>>> index_object((1,1,2,3,5), -2)
3
>>> index_object("abcdef...z", 0)
'a'
>>> index_object("abcdef...z", -1)
'z'
>>> index_object("abcdef...z", 100)
Traceback (most recent call last):
...
IndexError: string index out of range
>>> index_object(100, 100)
Traceback (most recent call last):
...
TypeError: 'int' object is unsubscriptable
"""
return o[i] return o[i]
# These make sure that our fast indexing works with large and unsigned types. # These make sure that our fast indexing works with large and unsigned types.
def test_unsigned_long(): def test_unsigned_long():
"""
>>> test_unsigned_long()
"""
cdef int i cdef int i
cdef unsigned long ix cdef unsigned long ix
cdef D = {} cdef D = {}
...@@ -80,6 +79,9 @@ def test_unsigned_long(): ...@@ -80,6 +79,9 @@ def test_unsigned_long():
assert len(D) == 0 assert len(D) == 0
def test_unsigned_short(): def test_unsigned_short():
"""
>>> test_unsigned_short()
"""
cdef int i cdef int i
cdef unsigned short ix cdef unsigned short ix
cdef D = {} cdef D = {}
...@@ -93,6 +95,9 @@ def test_unsigned_short(): ...@@ -93,6 +95,9 @@ def test_unsigned_short():
assert len(D) == 0 assert len(D) == 0
def test_long_long(): def test_long_long():
"""
>>> test_long_long()
"""
cdef int i cdef int i
cdef long long ix cdef long long ix
cdef D = {} cdef D = {}
......
__doc__ = u"""
>>> test(3)
3
"""
def test(x): def test(x):
"""
>>> test(3)
3
"""
return retinput(x) return retinput(x)
cdef inline int retinput(int x): cdef inline int retinput(int x):
o = x o = x
return o return o
__doc__ = u""" def f(a,b):
"""
>>> f(1,[1,2,3]) >>> f(1,[1,2,3])
True True
>>> f(5,[1,2,3]) >>> f(5,[1,2,3])
False False
>>> f(2,(1,2,3)) >>> f(2,(1,2,3))
True True
"""
result = a in b
return result
def g(a,b):
"""
>>> g(1,[1,2,3]) >>> g(1,[1,2,3])
1 1
>>> g(5,[1,2,3]) >>> g(5,[1,2,3])
0 0
>>> g(2,(1,2,3)) >>> g(2,(1,2,3))
1 1
"""
cdef int result
result = a in b
return result
def h(b):
"""
>>> h([1,2,3,4]) >>> h([1,2,3,4])
True True
>>> h([1,3,4]) >>> h([1,3,4])
False False
"""
result = 2 in b
return result
def j(b):
"""
>>> j([1,2,3,4]) >>> j([1,2,3,4])
1 1
>>> j([1,3,4]) >>> j([1,3,4])
0 0
"""
cdef int result
result = 2 in b
return result
def k(a):
"""
>>> k(1) >>> k(1)
1 1
>>> k(5) >>> k(5)
0 0
"""
cdef int result = a in [1,2,3,4]
return result
def m(int a):
"""
>>> m(2) >>> m(2)
1 1
>>> m(5) >>> m(5)
0 0
"""
cdef int result = a in [1,2,3,4]
return result
def n(a):
"""
>>> n('d *') >>> n('d *')
1 1
>>> n('xxx') >>> n('xxx')
0 0
"""
cdef int result = a.lower() in [u'a *',u'b *',u'c *',u'd *']
return result
def p(a):
"""
>>> p(1) >>> p(1)
0 0
>>> p('a') >>> p('a')
1 1
"""
cdef dict d = {u'a': 1, u'b': 2}
cdef int result = a in d
return result
def q(a):
"""
>>> q(1) >>> q(1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable TypeError: 'NoneType' object is not iterable
>>> l = [1,2,3,4]
>>> l = [1,2,3,4]
>>> l2 = [l[1:],l[:-1],l] >>> l2 = [l[1:],l[:-1],l]
>>> 2 in l in l2 >>> 2 in l in l2
True True
>>> r(2) """
1
>>> s(2)
1
"""
def f(a,b):
result = a in b
return result
def g(a,b):
cdef int result
result = a in b
return result
def h(b):
result = 2 in b
return result
def j(b):
cdef int result
result = 2 in b
return result
def k(a):
cdef int result = a in [1,2,3,4]
return result
def m(int a):
cdef int result = a in [1,2,3,4]
return result
def n(a):
cdef int result = a.lower() in [u'a *',u'b *',u'c *',u'd *']
return result
def p(a):
cdef dict d = {u'a': 1, u'b': 2}
cdef int result = a in d
return result
def q(a):
cdef dict d = None cdef dict d = None
cdef int result = a in d # should fail with a TypeError cdef int result = a in d # should fail with a TypeError
return result return result
def r(a): def r(a):
"""
>>> r(2)
1
"""
l = [1,2,3,4] l = [1,2,3,4]
l2 = [l[1:],l[:-1],l] l2 = [l[1:],l[:-1],l]
cdef int result = a in l in l2 cdef int result = a in l in l2
return result return result
def s(a): def s(a):
"""
>>> s(2)
1
"""
cdef int result = a in [1,2,3,4] in [[1,2,3],[2,3,4],[1,2,3,4]] cdef int result = a in [1,2,3,4] in [[1,2,3],[2,3,4],[1,2,3,4]]
return result return result
...@@ -2,27 +2,6 @@ __doc__ = u""" ...@@ -2,27 +2,6 @@ __doc__ = u"""
>>> str(f(5, 7)) >>> str(f(5, 7))
'29509034655744' '29509034655744'
>>> g(13, 4)
32
>>> h(56, 7)
105.0
>>> arrays()
19
>>> attributes()
26 26 26
>>> smoketest()
10
>>> test_side_effects()
side effect 1
c side effect 2
side effect 3
c side effect 4
([0, 11, 102, 3, 4], [0, 1, 2, 13, 104])
""" """
def f(a,b): def f(a,b):
...@@ -32,12 +11,20 @@ def f(a,b): ...@@ -32,12 +11,20 @@ def f(a,b):
return a return a
def g(int a, int b): def g(int a, int b):
"""
>>> g(13, 4)
32
"""
a -= b a -= b
a /= b a /= b
a <<= b a <<= b
return a return a
def h(double a, double b): def h(double a, double b):
"""
>>> h(56, 7)
105.0
"""
a /= b a /= b
a += b a += b
a *= b a *= b
...@@ -46,6 +33,10 @@ def h(double a, double b): ...@@ -46,6 +33,10 @@ def h(double a, double b):
cimport stdlib cimport stdlib
def arrays(): def arrays():
"""
>>> arrays()
19
"""
cdef char* buf = <char*>stdlib.malloc(10) cdef char* buf = <char*>stdlib.malloc(10)
cdef int i = 2 cdef int i = 2
cdef object j = 2 cdef object j = 2
...@@ -68,6 +59,10 @@ class B: ...@@ -68,6 +59,10 @@ class B:
attr = 3 attr = 3
def attributes(): def attributes():
"""
>>> attributes()
26 26 26
"""
cdef A a = A() cdef A a = A()
b = B() b = B()
a.attr += 10 a.attr += 10
...@@ -82,6 +77,10 @@ def get_2(): return 2 ...@@ -82,6 +77,10 @@ def get_2(): return 2
cdef int identity(int value): return value cdef int identity(int value): return value
def smoketest(): def smoketest():
"""
>>> smoketest()
10
"""
cdef char* buf = <char*>stdlib.malloc(10) cdef char* buf = <char*>stdlib.malloc(10)
cdef A a = A() cdef A a = A()
a.buf = buf a.buf = buf
...@@ -100,6 +99,14 @@ cdef int c_side_effect(int x): ...@@ -100,6 +99,14 @@ cdef int c_side_effect(int x):
return x return x
def test_side_effects(): def test_side_effects():
"""
>>> test_side_effects()
side effect 1
c side effect 2
side effect 3
c side effect 4
([0, 11, 102, 3, 4], [0, 1, 2, 13, 104])
"""
a = list(range(5)) a = list(range(5))
a[side_effect(1)] += 10 a[side_effect(1)] += 10
a[c_side_effect(2)] += 100 a[c_side_effect(2)] += 100
......
__doc__ = u"""
>>> c_longs()
(1, 1L, -1L, 18446744073709551615L)
>>> py_longs()
(1, 1L, 100000000000000000000000000000000L, -100000000000000000000000000000000L)
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u'L', u'') __doc__ = __doc__.replace(u'L', u'')
def c_longs(): def c_longs():
"""
>>> c_longs()
(1, 1L, -1L, 18446744073709551615L)
"""
cdef long a = 1L cdef long a = 1L
cdef unsigned long ua = 1UL cdef unsigned long ua = 1UL
cdef long long aa = 0xFFFFFFFFFFFFFFFFLL cdef long long aa = 0xFFFFFFFFFFFFFFFFLL
...@@ -19,4 +16,8 @@ def c_longs(): ...@@ -19,4 +16,8 @@ def c_longs():
return a, ua, aa, uaa return a, ua, aa, uaa
def py_longs(): def py_longs():
"""
>>> py_longs()
(1, 1L, 100000000000000000000000000000000L, -100000000000000000000000000000000L)
"""
return 1, 1L, 100000000000000000000000000000000, -100000000000000000000000000000000 return 1, 1L, 100000000000000000000000000000000, -100000000000000000000000000000000
__doc__ = u""" import sys
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '")
class C:
"""
>>> C().xxx(5) >>> C().xxx(5)
5 5
>>> C().xxx() >>> C().xxx()
...@@ -7,12 +12,6 @@ __doc__ = u""" ...@@ -7,12 +12,6 @@ __doc__ = u"""
42 42
>>> C().xxx() >>> C().xxx()
u'a b' u'a b'
""" """
import sys
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '")
class C:
def xxx(self, p=u"a b"): def xxx(self, p=u"a b"):
return p return p
__doc__ = u"""
>>> test_all()
True
"""
cdef class A: cdef class A:
pass pass
...@@ -9,6 +5,10 @@ import sys ...@@ -9,6 +5,10 @@ import sys
IS_PY3 = sys.version_info[0] >= 3 IS_PY3 = sys.version_info[0] >= 3
def test_all(): def test_all():
"""
>>> test_all()
True
"""
if IS_PY3: if IS_PY3:
new_type = type(u'a',(),{}) new_type = type(u'a',(),{})
else: else:
......
__doc__ = u""" def test_and(a,b):
"""
>>> test_and(None, None) >>> test_and(None, None)
True True
>>> test_and(None, 1) >>> test_and(None, 1)
False False
>>> test_and(1, None) >>> test_and(1, None)
False False
"""
return a is None and b is None
def test_more(a,b):
"""
>>> test_more(None, None) >>> test_more(None, None)
True True
>>> test_more(None, 1) >>> test_more(None, 1)
...@@ -14,7 +19,11 @@ __doc__ = u""" ...@@ -14,7 +19,11 @@ __doc__ = u"""
False False
>>> test_more(None, 0) >>> test_more(None, 0)
False False
"""
return a is None and (b is None or b == 1)
def test_more_c(a,b):
"""
>>> test_more_c(None, None) >>> test_more_c(None, None)
True True
>>> test_more_c(None, 1) >>> test_more_c(None, 1)
...@@ -23,13 +32,5 @@ __doc__ = u""" ...@@ -23,13 +32,5 @@ __doc__ = u"""
False False
>>> test_more_c(None, 0) >>> test_more_c(None, 0)
False False
""" """
def test_and(a,b):
return a is None and b is None
def test_more(a,b):
return a is None and (b is None or b == 1)
def test_more_c(a,b):
return (a is None or 1 == 2) and (b is None or b == 1) return (a is None or 1 == 2) and (b is None or b == 1)
__doc__ = u"""
>>> f()
"""
class IteratorAndIterateable: class IteratorAndIterateable:
def next(self): def next(self):
raise ValueError raise ValueError
...@@ -11,6 +7,9 @@ class IteratorAndIterateable: ...@@ -11,6 +7,9 @@ class IteratorAndIterateable:
return self return self
def f(): def f():
"""
>>> f()
"""
try: try:
for x in IteratorAndIterateable(): for x in IteratorAndIterateable():
pass pass
......
__doc__ = u""" dict_size = 4
>>> dict_size = 4 d = dict(zip(range(10,dict_size+10), range(dict_size)))
>>> d = dict(zip(range(10,dict_size+10), range(dict_size)))
>>> items(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
>>> iteritems(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
>>> iteritems_int(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
>>> iteritems_tuple(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
>>> iterkeys(d)
[10, 11, 12, 13]
>>> iterkeys_int(d)
[10, 11, 12, 13]
>>> iterdict(d)
[10, 11, 12, 13]
>>> iterdict_reassign(d)
[10, 11, 12, 13]
>>> iterdict_int(d)
[10, 11, 12, 13]
>>> itervalues(d)
[0, 1, 2, 3]
>>> itervalues_int(d)
[0, 1, 2, 3]
"""
def items(dict d): def items(dict d):
"""
>>> items(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
"""
l = [] l = []
for k,v in d.items(): for k,v in d.items():
l.append((k,v)) l.append((k,v))
...@@ -34,6 +13,10 @@ def items(dict d): ...@@ -34,6 +13,10 @@ def items(dict d):
return l return l
def iteritems(dict d): def iteritems(dict d):
"""
>>> iteritems(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
"""
l = [] l = []
for k,v in d.iteritems(): for k,v in d.iteritems():
l.append((k,v)) l.append((k,v))
...@@ -41,6 +24,10 @@ def iteritems(dict d): ...@@ -41,6 +24,10 @@ def iteritems(dict d):
return l return l
def iteritems_int(dict d): def iteritems_int(dict d):
"""
>>> iteritems_int(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
"""
cdef int k,v cdef int k,v
l = [] l = []
for k,v in d.iteritems(): for k,v in d.iteritems():
...@@ -49,6 +36,10 @@ def iteritems_int(dict d): ...@@ -49,6 +36,10 @@ def iteritems_int(dict d):
return l return l
def iteritems_tuple(dict d): def iteritems_tuple(dict d):
"""
>>> iteritems_tuple(d)
[(10, 0), (11, 1), (12, 2), (13, 3)]
"""
l = [] l = []
for t in d.iteritems(): for t in d.iteritems():
l.append(t) l.append(t)
...@@ -61,6 +52,10 @@ def iteritems_listcomp(dict d): ...@@ -61,6 +52,10 @@ def iteritems_listcomp(dict d):
return l return l
def iterkeys(dict d): def iterkeys(dict d):
"""
>>> iterkeys(d)
[10, 11, 12, 13]
"""
l = [] l = []
for k in d.iterkeys(): for k in d.iterkeys():
l.append(k) l.append(k)
...@@ -68,6 +63,10 @@ def iterkeys(dict d): ...@@ -68,6 +63,10 @@ def iterkeys(dict d):
return l return l
def iterkeys_int(dict d): def iterkeys_int(dict d):
"""
>>> iterkeys_int(d)
[10, 11, 12, 13]
"""
cdef int k cdef int k
l = [] l = []
for k in d.iterkeys(): for k in d.iterkeys():
...@@ -76,6 +75,10 @@ def iterkeys_int(dict d): ...@@ -76,6 +75,10 @@ def iterkeys_int(dict d):
return l return l
def iterdict(dict d): def iterdict(dict d):
"""
>>> iterdict(d)
[10, 11, 12, 13]
"""
l = [] l = []
for k in d: for k in d:
l.append(k) l.append(k)
...@@ -83,6 +86,10 @@ def iterdict(dict d): ...@@ -83,6 +86,10 @@ def iterdict(dict d):
return l return l
def iterdict_int(dict d): def iterdict_int(dict d):
"""
>>> iterdict_int(d)
[10, 11, 12, 13]
"""
cdef int k cdef int k
l = [] l = []
for k in d: for k in d:
...@@ -91,6 +98,10 @@ def iterdict_int(dict d): ...@@ -91,6 +98,10 @@ def iterdict_int(dict d):
return l return l
def iterdict_reassign(dict d): def iterdict_reassign(dict d):
"""
>>> iterdict_reassign(d)
[10, 11, 12, 13]
"""
cdef dict d_new = {} cdef dict d_new = {}
l = [] l = []
for k in d: for k in d:
...@@ -105,6 +116,10 @@ def iterdict_listcomp(dict d): ...@@ -105,6 +116,10 @@ def iterdict_listcomp(dict d):
return l return l
def itervalues(dict d): def itervalues(dict d):
"""
>>> itervalues(d)
[0, 1, 2, 3]
"""
l = [] l = []
for v in d.itervalues(): for v in d.itervalues():
l.append(v) l.append(v)
...@@ -112,6 +127,10 @@ def itervalues(dict d): ...@@ -112,6 +127,10 @@ def itervalues(dict d):
return l return l
def itervalues_int(dict d): def itervalues_int(dict d):
"""
>>> itervalues_int(d)
[0, 1, 2, 3]
"""
cdef int v cdef int v
l = [] l = []
for v in d.itervalues(): for v in d.itervalues():
......
__doc__ = u"""
>>> uf()
It works!
>>> bf()
It works!
"""
DEF USTUFF = u"Spam" DEF USTUFF = u"Spam"
def uf(): def uf():
"""
>>> uf()
It works!
"""
IF USTUFF == u"Spam": IF USTUFF == u"Spam":
print "It works!" print "It works!"
ELSE: ELSE:
...@@ -16,6 +13,10 @@ def uf(): ...@@ -16,6 +13,10 @@ def uf():
DEF BSTUFF = b"Spam" DEF BSTUFF = b"Spam"
def bf(): def bf():
"""
>>> bf()
It works!
"""
IF BSTUFF == b"Spam": IF BSTUFF == b"Spam":
print "It works!" print "It works!"
ELSE: ELSE:
......
__doc__ = u""" import sys
def test(**kw):
"""
>>> d = {1 : 2} >>> d = {1 : 2}
>>> test(**d) >>> test(**d)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: test() keywords must be strings TypeError: test() keywords must be strings
>>> d >>> d
{1: 2} {1: 2}
>>> d = {} >>> d = {}
>>> test(**d) >>> test(**d)
{'arg': 3} {'arg': 3}
>>> d >>> d
{} {}
>>> d = {'arg' : 2} # this should be u'arg', but Py2 can't handle it... >>> d = {'arg' : 2} # this should be u'arg', but Py2 can't handle it...
>>> test(**d) >>> test(**d)
{'arg': 3} {'arg': 3}
>>> d >>> d
{'arg': 2} {'arg': 2}
""" """
import sys
def test(**kw):
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
kw[u'arg'] = 3 kw[u'arg'] = 3
else: else:
......
__doc__ = u""" def b(a, b, c):
"""
>>> b(1,2,3) >>> b(1,2,3)
>>> b(1,2,3,4) >>> b(1,2,3,4)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: b() takes exactly 3 positional arguments (4 given) TypeError: b() takes exactly 3 positional arguments (4 given)
"""
a, b, c = b, c, a
def c(a, b, c=1):
"""
>>> c(1,2) >>> c(1,2)
>>> c(1,2,3) >>> c(1,2,3)
>>> c(1,2,3,4) >>> c(1,2,3,4)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: c() takes at most 3 positional arguments (4 given) TypeError: c() takes at most 3 positional arguments (4 given)
"""
a, b, c = b, c, a
def d(a, b, *, c = 88):
"""
>>> d(1,2) >>> d(1,2)
>>> d(1,2, c=1) >>> d(1,2, c=1)
>>> d(1,2,3) >>> d(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: d() takes exactly 2 positional arguments (3 given) TypeError: d() takes exactly 2 positional arguments (3 given)
>>> d(1,2, d=1) >>> d(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: d() got an unexpected keyword argument 'd' TypeError: d() got an unexpected keyword argument 'd'
"""
a, b, c = b, c, a
def e(a, b, c = 88, **kwds):
"""
>>> e(1,2) >>> e(1,2)
>>> e(1,2, c=1) >>> e(1,2, c=1)
>>> e(1,2, d=1) >>> e(1,2, d=1)
...@@ -28,10 +40,13 @@ __doc__ = u""" ...@@ -28,10 +40,13 @@ __doc__ = u"""
>>> e(1,2,3,4) >>> e(1,2,3,4)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: e() takes at most 3 positional arguments (4 given) TypeError: e() takes at most 3 positional arguments (4 given)
"""
a, b, c = b, c, a
def f(a, b, *, c, d = 42):
"""
>>> f(1,2, c=1) >>> f(1,2, c=1)
>>> f(1,2, c=1, d=2) >>> f(1,2, c=1, d=2)
>>> f(1,2,3) >>> f(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (3 given) TypeError: f() takes exactly 2 positional arguments (3 given)
...@@ -41,11 +56,14 @@ __doc__ = u""" ...@@ -41,11 +56,14 @@ __doc__ = u"""
>>> f(1,2, c=1, e=2) >>> f(1,2, c=1, e=2)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'e' TypeError: f() got an unexpected keyword argument 'e'
"""
a, b, c, d = b, c, d, a
def g(a, b, *, c, d = 42, e = 17, f, **kwds):
"""
>>> g(1,2, c=1, f=2) >>> g(1,2, c=1, f=2)
>>> g(1,2, c=1, e=0, f=2, d=11) >>> g(1,2, c=1, e=0, f=2, d=11)
>>> g(1,2, c=1, f=2, e=0, x=25) >>> g(1,2, c=1, f=2, e=0, x=25)
>>> g(1,2,3) >>> g(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: g() takes exactly 2 positional arguments (3 given) TypeError: g() takes exactly 2 positional arguments (3 given)
...@@ -55,81 +73,64 @@ __doc__ = u""" ...@@ -55,81 +73,64 @@ __doc__ = u"""
>>> g(1,2, c=1) >>> g(1,2, c=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: g() needs keyword-only argument f TypeError: g() needs keyword-only argument f
"""
a, b, c, d, e, f = b, c, d, e, f, a
def h(a, b, *args, c, d = 42, e = 17, f, **kwds):
"""
>>> h(1,2, c=1, f=2) >>> h(1,2, c=1, f=2)
>>> h(1,2, c=1, f=2, e=3) >>> h(1,2, c=1, f=2, e=3)
>>> h(1,2,3,4,5,6, c=1, f=2) >>> h(1,2,3,4,5,6, c=1, f=2)
>>> h(1,2,3,4,5,6, c=1, f=2, e=3, x=25, y=11) >>> h(1,2,3,4,5,6, c=1, f=2, e=3, x=25, y=11)
>>> h(1,2,3) >>> h(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: h() needs keyword-only argument c TypeError: h() needs keyword-only argument c
>>> h(1,2, d=1) >>> h(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: h() needs keyword-only argument c TypeError: h() needs keyword-only argument c
"""
a, b, c, d, e, f = b, c, d, e, f, a
def k(a, b, c=1, *args, d = 42, e = 17, f, **kwds):
"""
>>> k(1,2, c=1, f=2) >>> k(1,2, c=1, f=2)
>>> k(1,2, c=1, f=2, e=3) >>> k(1,2, c=1, f=2, e=3)
>>> k(1,2,3,4,5,6, d=1, f=2) >>> k(1,2,3,4,5,6, d=1, f=2)
>>> k(1,2,3,4,5,6, d=1, f=2, e=3, x=25, y=11) >>> k(1,2,3,4,5,6, d=1, f=2, e=3, x=25, y=11)
>>> k(1,2,3) >>> k(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: k() needs keyword-only argument f TypeError: k() needs keyword-only argument f
>>> k(1,2, d=1) >>> k(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: k() needs keyword-only argument f TypeError: k() needs keyword-only argument f
"""
a, b, c, d, e, f = b, c, d, e, f, a
def l(*, a, b, c = 88):
"""
>>> l(a=1, b=2) >>> l(a=1, b=2)
>>> l(a=1, b=2, c=1) >>> l(a=1, b=2, c=1)
>>> l(1,2,3) >>> l(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: l() takes exactly 0 positional arguments (3 given) TypeError: l() takes exactly 0 positional arguments (3 given)
>>> l(1,2, d=1) >>> l(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: l() takes exactly 0 positional arguments (2 given) TypeError: l() takes exactly 0 positional arguments (2 given)
>>> m(1, b=2)
>>> m(a=1, b=2)
>>> m(a=1, b=2, c=1)
>>> l(1,2,3) >>> l(1,2,3)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: l() takes exactly 0 positional arguments (3 given) TypeError: l() takes exactly 0 positional arguments (3 given)
>>> l(1,2, d=1) >>> l(1,2, d=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: l() takes exactly 0 positional arguments (2 given) TypeError: l() takes exactly 0 positional arguments (2 given)
""" """
def b(a, b, c):
a, b, c = b, c, a
def c(a, b, c=1):
a, b, c = b, c, a
def d(a, b, *, c = 88):
a, b, c = b, c, a
def e(a, b, c = 88, **kwds):
a, b, c = b, c, a
def f(a, b, *, c, d = 42):
a, b, c, d = b, c, d, a
def g(a, b, *, c, d = 42, e = 17, f, **kwds):
a, b, c, d, e, f = b, c, d, e, f, a
def h(a, b, *args, c, d = 42, e = 17, f, **kwds):
a, b, c, d, e, f = b, c, d, e, f, a
def k(a, b, c=1, *args, d = 42, e = 17, f, **kwds):
a, b, c, d, e, f = b, c, d, e, f, a
def l(*, a, b, c = 88):
a, b, c = b, c, a a, b, c = b, c, a
def m(a, *, b, c = 88): def m(a, *, b, c = 88):
"""
>>> m(1, b=2)
>>> m(a=1, b=2)
>>> m(a=1, b=2, c=1)
"""
a, b, c = b, c, a a, b, c = b, c, a
def n(a, *, b, c = 88): def n(a, *, b, c = 88):
......
__doc__ = u""" # the calls:
def call0ab(f):
"""
>>> call0ab(b) >>> call0ab(b)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: b() takes exactly 3 positional arguments (2 given) TypeError: b() takes exactly 3 positional arguments (2 given)
>>> call0abc(b)
1 2 3
>>> call3(b)
1 2 3
>>> call4(b)
Traceback (most recent call last):
TypeError: b() takes exactly 3 positional arguments (4 given)
>>> call0ab(c) >>> call0ab(c)
1 2 1 1 2 1
>>> call0abc(c) >>> call0ab(d)
1 2 88
"""
f(a=1,b=2)
def call0abc(f):
"""
>>> call0abc(b)
1 2 3 1 2 3
>>> call2(c) >>> call0abc(c)
1 2 1
>>> call3(c)
1 2 3 1 2 3
>>> call4(c)
Traceback (most recent call last):
TypeError: c() takes at most 3 positional arguments (4 given)
>>> call0abc(d) >>> call0abc(d)
1 2 3 1 2 3
>>> call0ab(d) >>> call0abc(e)
1 2 88 1 2 3 []
>>> call0abc(f)
1 2 3 42
>>> call0abc(m)
1 2 3
"""
f(a=1,b=2,c=3)
def call2(f):
"""
>>> call2(c)
1 2 1
>>> call2(d) >>> call2(d)
1 2 88 1 2 88
>>> call2c(d) >>> call2(e)
1 2 1 1 2 88 []
>>> call2(f)
Traceback (most recent call last):
TypeError: f() needs keyword-only argument c
>>> call2(g)
Traceback (most recent call last):
TypeError: g() needs keyword-only argument c
>>> call2(m)
Traceback (most recent call last):
TypeError: m() needs keyword-only argument c
"""
f(1,2)
def call3(f):
"""
>>> call3(b)
1 2 3
>>> call3(c)
1 2 3
>>> call3(d) >>> call3(d)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: d() takes exactly 2 positional arguments (3 given) TypeError: d() takes exactly 2 positional arguments (3 given)
>>> call2d(d)
Traceback (most recent call last):
TypeError: d() got an unexpected keyword argument 'd'
>>> call0abc(e)
1 2 3 []
>>> call2(e)
1 2 88 []
>>> call2c(e)
1 2 1 []
>>> call2d(e)
1 2 88 [('d', 1)]
>>> call2cde(e)
1 2 1 [('d', 2), ('e', 3)]
>>> call3(e) >>> call3(e)
1 2 3 [] 1 2 3 []
>>> call4(e)
Traceback (most recent call last):
TypeError: e() takes at most 3 positional arguments (4 given)
>>> call0abc(f)
1 2 3 42
>>> call2c(f)
1 2 1 42
>>> call2cd(f)
1 2 1 2
>>> call3(f) >>> call3(f)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (3 given) TypeError: f() takes exactly 2 positional arguments (3 given)
>>> call2(f)
Traceback (most recent call last):
TypeError: f() needs keyword-only argument c
>>> call2ce(f)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'e'
>>> call2cf(g)
1 2 1 42 17 2 []
>>> call2cefd(g)
1 2 1 11 0 2 []
>>> call2cfex(g)
1 2 1 42 0 2 [('x', 25)]
>>> call3(g) >>> call3(g)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: g() takes exactly 2 positional arguments (3 given) TypeError: g() takes exactly 2 positional arguments (3 given)
>>> call2(g)
Traceback (most recent call last):
TypeError: g() needs keyword-only argument c
>>> call2c(g)
Traceback (most recent call last):
TypeError: g() needs keyword-only argument f
>>> call2cf(h)
1 2 1 42 17 2 () []
>>> call2cfe(h)
1 2 1 42 3 2 () []
>>> call6cf(h)
1 2 1 42 17 2 (3, 4, 5, 6) []
>>> call6cfexy(h)
1 2 1 42 3 2 (3, 4, 5, 6) [('x', 25), ('y', 11)]
>>> call3(h) >>> call3(h)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: h() needs keyword-only argument c TypeError: h() needs keyword-only argument c
>>> call3d(h)
Traceback (most recent call last):
TypeError: h() needs keyword-only argument c
>>> call2cf(k)
1 2 1 42 17 2 () []
>>> call2cfe(k)
1 2 1 42 3 2 () []
>>> call6df(k)
1 2 3 1 17 2 (4, 5, 6) []
>>> call6dfexy(k)
1 2 3 1 3 2 (4, 5, 6) [('x', 25), ('y', 11)]
>>> call3(k) >>> call3(k)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: k() needs keyword-only argument f TypeError: k() needs keyword-only argument f
>>> call2d(k)
Traceback (most recent call last):
TypeError: k() needs keyword-only argument f
>>> call0abc(m)
1 2 3
>>> call2c(m)
1 2 1
>>> call3(m) >>> call3(m)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: m() takes at most 2 positional arguments (3 given) TypeError: m() takes at most 2 positional arguments (3 given)
>>> call2(m) """
Traceback (most recent call last):
TypeError: m() needs keyword-only argument c
>>> call2cd(m)
Traceback (most recent call last):
TypeError: m() got an unexpected keyword argument 'd'
"""
# the calls:
def call0ab(f):
f(a=1,b=2)
def call0abc(f):
f(a=1,b=2,c=3)
def call2(f):
f(1,2)
def call3(f):
f(1,2,3) f(1,2,3)
def call4(f): def call4(f):
"""
>>> call4(b)
Traceback (most recent call last):
TypeError: b() takes exactly 3 positional arguments (4 given)
>>> call4(c)
Traceback (most recent call last):
TypeError: c() takes at most 3 positional arguments (4 given)
>>> call4(e)
Traceback (most recent call last):
TypeError: e() takes at most 3 positional arguments (4 given)
"""
f(1,2,3,4) f(1,2,3,4)
def call2c(f): def call2c(f):
"""
>>> call2c(d)
1 2 1
>>> call2c(e)
1 2 1 []
>>> call2c(f)
1 2 1 42
>>> call2c(g)
Traceback (most recent call last):
TypeError: g() needs keyword-only argument f
>>> call2c(m)
1 2 1
"""
f(1,2, c=1) f(1,2, c=1)
def call2d(f): def call2d(f):
"""
>>> call2d(d)
Traceback (most recent call last):
TypeError: d() got an unexpected keyword argument 'd'
>>> call2d(e)
1 2 88 [('d', 1)]
>>> call2d(k)
Traceback (most recent call last):
TypeError: k() needs keyword-only argument f
"""
f(1,2, d=1) f(1,2, d=1)
def call3d(f): def call3d(f):
"""
>>> call3d(h)
Traceback (most recent call last):
TypeError: h() needs keyword-only argument c
"""
f(1,2,3, d=1) f(1,2,3, d=1)
def call2cd(f): def call2cd(f):
"""
>>> call2cd(f)
1 2 1 2
>>> call2cd(m)
Traceback (most recent call last):
TypeError: m() got an unexpected keyword argument 'd'
"""
f(1,2, c=1, d=2) f(1,2, c=1, d=2)
def call2ce(f): def call2ce(f):
"""
>>> call2ce(f)
Traceback (most recent call last):
TypeError: f() got an unexpected keyword argument 'e'
"""
f(1,2, c=1, e=2) f(1,2, c=1, e=2)
def call2cde(f): def call2cde(f):
"""
>>> call2cde(e)
1 2 1 [('d', 2), ('e', 3)]
"""
f(1,2, c=1, d=2, e=3) f(1,2, c=1, d=2, e=3)
def call2cf(f): def call2cf(f):
"""
>>> call2cf(g)
1 2 1 42 17 2 []
>>> call2cf(h)
1 2 1 42 17 2 () []
>>> call2cf(k)
1 2 1 42 17 2 () []
"""
f(1,2, c=1, f=2) f(1,2, c=1, f=2)
def call6cf(f): def call6cf(f):
"""
>>> call6cf(h)
1 2 1 42 17 2 (3, 4, 5, 6) []
"""
f(1,2,3,4,5,6, c=1, f=2) f(1,2,3,4,5,6, c=1, f=2)
def call6df(f): def call6df(f):
"""
>>> call6df(k)
1 2 3 1 17 2 (4, 5, 6) []
"""
f(1,2,3,4,5,6, d=1, f=2) f(1,2,3,4,5,6, d=1, f=2)
def call2cfe(f): def call2cfe(f):
"""
>>> call2cfe(h)
1 2 1 42 3 2 () []
>>> call2cfe(k)
1 2 1 42 3 2 () []
"""
f(1,2, c=1, f=2, e=3) f(1,2, c=1, f=2, e=3)
def call2cefd(f): def call2cefd(f):
"""
>>> call2cefd(g)
1 2 1 11 0 2 []
"""
f(1,2, c=1, e=0, f=2, d=11) f(1,2, c=1, e=0, f=2, d=11)
def call2cfex(f): def call2cfex(f):
"""
>>> call2cfex(g)
1 2 1 42 0 2 [('x', 25)]
"""
f(1,2, c=1, f=2, e=0, x=25) f(1,2, c=1, f=2, e=0, x=25)
def call6argscfexy(f): def call6argscfexy(f):
...@@ -194,9 +207,17 @@ def call6argscfexy(f): ...@@ -194,9 +207,17 @@ def call6argscfexy(f):
f(*args, c=1, f=2, e=3, x=25, y=11) f(*args, c=1, f=2, e=3, x=25, y=11)
def call6cfexy(f): def call6cfexy(f):
"""
>>> call6cfexy(h)
1 2 1 42 3 2 (3, 4, 5, 6) [('x', 25), ('y', 11)]
"""
f(1,2,3,4,5,6, c=1, f=2, e=3, x=25, y=11) f(1,2,3,4,5,6, c=1, f=2, e=3, x=25, y=11)
def call6dfexy(f): def call6dfexy(f):
"""
>>> call6dfexy(k)
1 2 3 1 3 2 (4, 5, 6) [('x', 25), ('y', 11)]
"""
f(1,2,3,4,5,6, d=1, f=2, e=3, x=25, y=11) f(1,2,3,4,5,6, d=1, f=2, e=3, x=25, y=11)
# the called functions: # the called functions:
......
__doc__ = u"""
>>> add_large_pow() == 2**31 + 2**31
True
>>> add_large_pow() == 2**32
True
>>> add_large() == 2147483647 + 2147483647
True
#>>> add_large_c() == 2147483647 + 2147483647
#True
"""
#def add_large_c(): #def add_large_c():
# cdef unsigned long long val = 2**30 + 2**30 # cdef unsigned long long val = 2**30 + 2**30
# return val # return val
def add_large(): def add_large():
"""
>>> add_large() == 2147483647 + 2147483647
True
#>>> add_large_c() == 2147483647 + 2147483647
#True
"""
return 2147483647 + 2147483647 return 2147483647 + 2147483647
def add_large_pow(): def add_large_pow():
"""
>>> add_large_pow() == 2**31 + 2**31
True
>>> add_large_pow() == 2**32
True
"""
return 2**31 + 2**31 return 2**31 + 2**31
__doc__ = u""" def f(obj1, obj2, obj3, obj4, obj5):
"""
>>> f(1, 2, 3, 4, 5) >>> f(1, 2, 3, 4, 5)
[] []
>>> g(1, 2, 3, 4, 5) """
[2]
>>> h(1, 2, 3, 4, 5)
[2, 3]
>>> j(1, 2, 3, 4, 5)
[2, 3, 4]
>>> k(1, 2, 3, 4, 5)
[17, 42, 88]
>>> test_list_sort()
[1, 2, 3, 4]
>>> test_list_reverse()
[1, 2, 3, 4]
>>> test_list_pop()
(2, [1])
>>> test_list_pop0()
(1, [2])
>>> test_list_pop_all()
True
"""
def f(obj1, obj2, obj3, obj4, obj5):
obj1 = [] obj1 = []
return obj1 return obj1
def g(obj1, obj2, obj3, obj4, obj5): def g(obj1, obj2, obj3, obj4, obj5):
"""
>>> g(1, 2, 3, 4, 5)
[2]
"""
obj1 = [obj2] obj1 = [obj2]
return obj1 return obj1
def h(obj1, obj2, obj3, obj4, obj5): def h(obj1, obj2, obj3, obj4, obj5):
"""
>>> h(1, 2, 3, 4, 5)
[2, 3]
"""
obj1 = [obj2, obj3] obj1 = [obj2, obj3]
return obj1 return obj1
def j(obj1, obj2, obj3, obj4, obj5): def j(obj1, obj2, obj3, obj4, obj5):
"""
>>> j(1, 2, 3, 4, 5)
[2, 3, 4]
"""
obj1 = [obj2, obj3, obj4] obj1 = [obj2, obj3, obj4]
return obj1 return obj1
def k(obj1, obj2, obj3, obj4, obj5): def k(obj1, obj2, obj3, obj4, obj5):
"""
>>> k(1, 2, 3, 4, 5)
[17, 42, 88]
"""
obj1 = [17, 42, 88] obj1 = [17, 42, 88]
return obj1 return obj1
def test_list_sort(): def test_list_sort():
"""
>>> test_list_sort()
[1, 2, 3, 4]
"""
cdef list l1 cdef list l1
l1 = [2,3,1,4] l1 = [2,3,1,4]
l1.sort() l1.sort()
...@@ -54,24 +55,40 @@ def test_list_sort_reversed(): ...@@ -54,24 +55,40 @@ def test_list_sort_reversed():
return l1 return l1
def test_list_reverse(): def test_list_reverse():
"""
>>> test_list_reverse()
[1, 2, 3, 4]
"""
cdef list l1 cdef list l1
l1 = [4,3,2,1] l1 = [4,3,2,1]
l1.reverse() l1.reverse()
return l1 return l1
def test_list_pop(): def test_list_pop():
"""
>>> test_list_pop()
(2, [1])
"""
cdef list l1 cdef list l1
l1 = [1,2] l1 = [1,2]
two = l1.pop() two = l1.pop()
return two, l1 return two, l1
def test_list_pop0(): def test_list_pop0():
"""
>>> test_list_pop0()
(1, [2])
"""
cdef list l1 cdef list l1
l1 = [1,2] l1 = [1,2]
one = l1.pop(0) one = l1.pop(0)
return one, l1 return one, l1
def test_list_pop_all(): def test_list_pop_all():
"""
>>> test_list_pop_all()
True
"""
cdef list l1 cdef list l1
l1 = [1,2] l1 = [1,2]
try: try:
......
__doc__ = u"""
>>> smoketest()
[0, 4, 8]
>>> int_runvar()
[0, 4, 8]
>>> typed()
[A, A, A]
>>> iterdict()
[1, 2, 3]
"""
def smoketest(): def smoketest():
"""
>>> smoketest()
[0, 4, 8]
"""
print [x*2 for x in range(5) if x % 2 == 0] print [x*2 for x in range(5) if x % 2 == 0]
def int_runvar(): def int_runvar():
"""
>>> int_runvar()
[0, 4, 8]
"""
cdef int x cdef int x
print [x*2 for x in range(5) if x % 2 == 0] print [x*2 for x in range(5) if x % 2 == 0]
...@@ -20,10 +17,18 @@ cdef class A: ...@@ -20,10 +17,18 @@ cdef class A:
def __repr__(self): return u"A" def __repr__(self): return u"A"
def typed(): def typed():
"""
>>> typed()
[A, A, A]
"""
cdef A obj cdef A obj
print [obj for obj in [A(), A(), A()]] print [obj for obj in [A(), A(), A()]]
def iterdict(): def iterdict():
"""
>>> iterdict()
[1, 2, 3]
"""
cdef dict d = dict(a=1,b=2,c=3) cdef dict d = dict(a=1,b=2,c=3)
l = [d[key] for key in d] l = [d[key] for key in d]
l.sort() l.sort()
......
__doc__ = u""" __doc__ = """
>>> test_ints(100)
(100, 100, 100)
>>> test_chars(b'yo') >>> test_chars(b'yo')
(b'a', b'bc', b'yo') (b'a', b'bc', b'yo')
>>> test_chars(None) # doctest: +ELLIPSIS >>> test_chars(None) # doctest: +ELLIPSIS
Traceback (most recent call last): Traceback (most recent call last):
TypeError: expected ... TypeError: expected ...
>>> test_struct(-5, -10)
-5 -10 True
1 2 False
""" """
import sys import sys
...@@ -17,6 +12,10 @@ if sys.version_info[0] < 3: ...@@ -17,6 +12,10 @@ if sys.version_info[0] < 3:
__doc__ = __doc__.replace(u"b'", u"'") __doc__ = __doc__.replace(u"b'", u"'")
def test_ints(int x): def test_ints(int x):
"""
>>> test_ints(100)
(100, 100, 100)
"""
cdef list L = [1,2,3,x] cdef list L = [1,2,3,x]
cdef int* Li = [1,2,3,x] cdef int* Li = [1,2,3,x]
cdef int** Lii = [Li, &x] cdef int** Lii = [Li, &x]
...@@ -35,6 +34,11 @@ cdef print_struct(MyStruct a): ...@@ -35,6 +34,11 @@ cdef print_struct(MyStruct a):
print a.x, a.y, a.data == NULL print a.x, a.y, a.data == NULL
def test_struct(int x, y): def test_struct(int x, y):
"""
>>> test_struct(-5, -10)
-5 -10 True
1 2 False
"""
cdef MyStruct* aa = [[x,y, NULL], [x+1,y+1,NULL]] cdef MyStruct* aa = [[x,y, NULL], [x+1,y+1,NULL]]
print_struct(aa[0]) print_struct(aa[0])
print_struct([1, 2, <double**>1]) print_struct([1, 2, <double**>1])
......
__doc__ = u"""
>>> foo()
>>> test_float(1./3)
True
>>> test_complex(1j/3)
True
"""
def foo(): def foo():
"""
>>> foo()
"""
a = 42 a = 42
a1 = 0123 a1 = 0123
a2 = 0xabc a2 = 0xabc
...@@ -55,7 +50,15 @@ with ' and " quotes""" ...@@ -55,7 +50,15 @@ with ' and " quotes"""
def test_float(x): def test_float(x):
"""
>>> test_float(1./3)
True
"""
return x == 1./3 return x == 1./3
def test_complex(x): def test_complex(x):
"""
>>> test_complex(1j/3)
True
"""
return x == 0.3333333333333333j return x == 0.3333333333333333j
...@@ -2,12 +2,6 @@ __doc__ = u""" ...@@ -2,12 +2,6 @@ __doc__ = u"""
>>> sorted( get_locals(1,2,3, k=5) .items()) >>> sorted( get_locals(1,2,3, k=5) .items())
[('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)] [('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)]
>>> in_locals('z')
True
>>> in_locals('args')
True
>>> in_locals('X')
False
""" """
def get_locals(x, *args, **kwds): def get_locals(x, *args, **kwds):
...@@ -16,6 +10,14 @@ def get_locals(x, *args, **kwds): ...@@ -16,6 +10,14 @@ def get_locals(x, *args, **kwds):
return locals() return locals()
def in_locals(x, *args, **kwds): def in_locals(x, *args, **kwds):
"""
>>> in_locals('z')
True
>>> in_locals('args')
True
>>> in_locals('X')
False
"""
cdef int z = 5 cdef int z = 5
y = "hi" y = "hi"
return x in locals() return x in locals()
......
...@@ -2,8 +2,6 @@ __doc__ = u""" ...@@ -2,8 +2,6 @@ __doc__ = u"""
>>> sorted( get_locals(1,2,3, k=5) .items()) >>> sorted( get_locals(1,2,3, k=5) .items())
[('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)] [('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)]
>>> get_locals_rebound(1,2,3)
'REBOUND'
""" """
def get_locals(x, *args, **kwds): def get_locals(x, *args, **kwds):
...@@ -12,6 +10,10 @@ def get_locals(x, *args, **kwds): ...@@ -12,6 +10,10 @@ def get_locals(x, *args, **kwds):
return locals() return locals()
def get_locals_rebound(x, *args, **kwds): def get_locals_rebound(x, *args, **kwds):
"""
>>> get_locals_rebound(1,2,3)
'REBOUND'
"""
cdef int z = 5 cdef int z = 5
locals = _locals locals = _locals
y = "hi" y = "hi"
......
__doc__ = u"""
>>> loops()
5
"""
def loops(): def loops():
"""
>>> loops()
5
"""
cdef int k cdef int k
for i from 0 <= i < 5: for i from 0 <= i < 5:
for j from 0 <= j < 2: for j from 0 <= j < 2:
......
__doc__ = u""" import sys
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '")
def f():
"""
>>> f() >>> f()
>>> g >>> g
42 42
...@@ -8,13 +13,7 @@ __doc__ = u""" ...@@ -8,13 +13,7 @@ __doc__ = u"""
u'eggs' u'eggs'
>>> z >>> z
u'spameggs' u'spameggs'
""" """
import sys
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '")
def f():
pass pass
g = 42 g = 42
......
__doc__ = u"""
>>> modobj(9,2)
1
>>> modobj('%d', 5)
'5'
>>> modint(9,2)
1
"""
import sys import sys
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
__doc__ = __doc__ + u""" __doc__ = u"""
>>> modptr() >>> modptr()
'spameggs' 'spameggs'
""" """
def modobj(obj2, obj3): def modobj(obj2, obj3):
"""
>>> modobj(9,2)
1
>>> modobj('%d', 5)
'5'
"""
obj1 = obj2 % obj3 obj1 = obj2 % obj3
return obj1 return obj1
def modint(int int2, int int3): def modint(int int2, int int3):
"""
>>> modint(9,2)
1
"""
cdef int int1 cdef int int1
int1 = int2 % int3 int1 = int2 % int3
return int1 return int1
...@@ -29,6 +28,5 @@ def modptr(): ...@@ -29,6 +28,5 @@ def modptr():
cdef char *str2, *str3 cdef char *str2, *str3
str2 = "spam%s" str2 = "spam%s"
str3 = "eggs" str3 = "eggs"
obj1 = str2 % str3 # '%' operator doesn't work on byte strings in Py3 obj1 = str2 % str3 # '%' operator doesn't work on byte strings in Py3
return obj1 return obj1
__doc__ = u""" __doc__ = """
>>> f()
(1, 2, 1, 2)
>>> g()
(1, 1, 2, 2, 3, 3)
>>> h() >>> h()
(1, b'test', 3, 1, b'test', 3) (1, b'test', 3, 1, b'test', 3)
>>> j()
(2, 1, 4, 2, 6, 3)
""" """
import sys import sys
...@@ -14,12 +8,20 @@ if sys.version_info[0] < 3: ...@@ -14,12 +8,20 @@ if sys.version_info[0] < 3:
__doc__ = __doc__.replace(u" b'", u" '") __doc__ = __doc__.replace(u" b'", u" '")
def f(): def f():
"""
>>> f()
(1, 2, 1, 2)
"""
cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b
obj1b, obj2b, obj3b = 1, 2, 3 obj1b, obj2b, obj3b = 1, 2, 3
obj1a, obj2a = obj1b, obj2b obj1a, obj2a = obj1b, obj2b
return obj1a, obj2a, obj1b, obj2b return obj1a, obj2a, obj1b, obj2b
def g(): def g():
"""
>>> g()
(1, 1, 2, 2, 3, 3)
"""
cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b
obj1b, obj2b, obj3b = 1, 2, 3 obj1b, obj2b, obj3b = 1, 2, 3
obj1a, [obj2a, obj3a] = [obj1b, (obj2b, obj3b)] obj1a, [obj2a, obj3a] = [obj1b, (obj2b, obj3b)]
...@@ -34,6 +36,10 @@ def h(): ...@@ -34,6 +36,10 @@ def h():
return int1, ptr1, obj1a, int2, ptr2, obj1b return int1, ptr1, obj1a, int2, ptr2, obj1b
def j(): def j():
"""
>>> j()
(2, 1, 4, 2, 6, 3)
"""
cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b cdef object obj1a, obj2a, obj3a, obj1b, obj2b, obj3b
obj1b, obj2b, obj3b = 1, 2, 3 obj1b, obj2b, obj3b = 1, 2, 3
obj1a, obj2a, obj3a = obj1b + 1, obj2b + 2, obj3b + 3 obj1a, obj2a, obj3a = obj1b + 1, obj2b + 2, obj3b + 3
......
__doc__ = u"""
>>> test(Exception(u'hi'))
Raising: Exception(u'hi',)
Caught: Exception(u'hi',)
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u"u'", u"'") __doc__ = __doc__.replace(u"u'", u"'")
...@@ -11,6 +5,11 @@ if sys.version_info[0] >= 3: ...@@ -11,6 +5,11 @@ if sys.version_info[0] >= 3:
import sys, types import sys, types
def test(obj): def test(obj):
"""
>>> test(Exception(u'hi'))
Raising: Exception(u'hi',)
Caught: Exception(u'hi',)
"""
print u"Raising: %s%r" % (obj.__class__.__name__, obj.args) print u"Raising: %s%r" % (obj.__class__.__name__, obj.args)
try: try:
raise obj raise obj
......
__doc__ = u"""
>>> test(5)
47
>>> test(11)
53
"""
def test(int x): def test(int x):
"""
>>> test(5)
47
>>> test(11)
53
"""
with nogil: with nogil:
f(x) f(x)
x = g(x) x = g(x)
...@@ -20,5 +19,3 @@ cdef int g(int x) nogil: ...@@ -20,5 +19,3 @@ cdef int g(int x) nogil:
cdef int y cdef int y
y = x + 42 y = x + 42
return y return y
__doc__ = u""" __doc__ = u"""
Tests accessing attributes of extension type variables Tests accessing attributes of extension type variables
set to None set to None
>>> obj = MyClass(2, 3)
>>> getattr_(obj)
2
>>> getattr_(None)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
>>> setattr_(obj)
>>> getattr_(obj)
10
>>> setattr_(None)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
>>> obj = MyClass(2, 3)
>>> checking(obj)
2
2
>>> checking(None)
var is None
>>> check_and_assign(obj)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
>>> check_buffer_get(None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is unsubscriptable
>>> check_buffer_set(None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is unsubscriptable
""" """
cimport cython cimport cython
...@@ -54,10 +13,30 @@ cdef class MyClass: ...@@ -54,10 +13,30 @@ cdef class MyClass:
@cython.nonecheck(True) @cython.nonecheck(True)
def getattr_(MyClass var): def getattr_(MyClass var):
"""
>>> obj = MyClass(2, 3)
>>> getattr_(obj)
2
>>> getattr_(None)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
>>> setattr_(obj)
>>> getattr_(obj)
10
"""
print var.a print var.a
@cython.nonecheck(True) @cython.nonecheck(True)
def setattr_(MyClass var): def setattr_(MyClass var):
"""
>>> obj = MyClass(2, 3)
>>> setattr_(obj)
>>> setattr_(None)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
"""
var.a = 10 var.a = 10
def some(): def some():
...@@ -65,6 +44,14 @@ def some(): ...@@ -65,6 +44,14 @@ def some():
@cython.nonecheck(True) @cython.nonecheck(True)
def checking(MyClass var): def checking(MyClass var):
"""
>>> obj = MyClass(2, 3)
>>> checking(obj)
2
2
>>> checking(None)
var is None
"""
state = (var is None) state = (var is None)
if not state: if not state:
print var.a print var.a
...@@ -75,6 +62,13 @@ def checking(MyClass var): ...@@ -75,6 +62,13 @@ def checking(MyClass var):
@cython.nonecheck(True) @cython.nonecheck(True)
def check_and_assign(MyClass var): def check_and_assign(MyClass var):
"""
>>> obj = MyClass(2, 3)
>>> check_and_assign(obj)
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'a'
"""
if var is not None: if var is not None:
print var.a print var.a
var = None var = None
...@@ -82,9 +76,20 @@ def check_and_assign(MyClass var): ...@@ -82,9 +76,20 @@ def check_and_assign(MyClass var):
@cython.nonecheck(True) @cython.nonecheck(True)
def check_buffer_get(object[int] buf): def check_buffer_get(object[int] buf):
"""
>>> check_buffer_get(None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is unsubscriptable
"""
return buf[0] return buf[0]
@cython.nonecheck(True) @cython.nonecheck(True)
def check_buffer_set(object[int] buf): def check_buffer_set(object[int] buf):
"""
>>> check_buffer_set(None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is unsubscriptable
"""
buf[0] = 1 buf[0] = 1
__doc__ = u"""
>>> g()
"""
cdef class Spam: cdef class Spam:
pass pass
...@@ -9,4 +5,7 @@ cdef f(Spam s): ...@@ -9,4 +5,7 @@ cdef f(Spam s):
pass pass
def g(): def g():
"""
>>> g()
"""
f(None) f(None)
__doc__ = u""" def f(a,b):
"""
>>> f(1,[1,2,3]) >>> f(1,[1,2,3])
False False
>>> f(5,[1,2,3]) >>> f(5,[1,2,3])
True True
>>> f(2,(1,2,3)) >>> f(2,(1,2,3))
False False
"""
result = a not in b
return result
def g(a,b):
"""
>>> g(1,[1,2,3]) >>> g(1,[1,2,3])
0 0
>>> g(5,[1,2,3]) >>> g(5,[1,2,3])
1 1
>>> g(2,(1,2,3)) >>> g(2,(1,2,3))
0 0
"""
cdef int result
result = a not in b
return result
def h(b):
"""
>>> h([1,2,3,4]) >>> h([1,2,3,4])
False False
>>> h([1,3,4]) >>> h([1,3,4])
True True
"""
result = 2 not in b
return result
def j(b):
"""
>>> j([1,2,3,4]) >>> j([1,2,3,4])
0 0
>>> j([1,3,4]) >>> j([1,3,4])
1 1
"""
cdef int result
result = 2 not in b
return result
def k(a):
"""
>>> k(1) >>> k(1)
0 0
>>> k(5) >>> k(5)
1 1
"""
cdef int result = a not in [1,2,3,4]
return result
def m(int a):
"""
>>> m(2) >>> m(2)
0 0
>>> m(5) >>> m(5)
1 1
"""
cdef int result = a not in [1,2,3,4]
return result
def n(a):
"""
>>> n('d *') >>> n('d *')
0 0
>>> n('xxx') >>> n('xxx')
1 1
"""
cdef int result = a.lower() not in [u'a *',u'b *',u'c *',u'd *']
return result
def p(a):
"""
>>> p('a') >>> p('a')
0 0
>>> p(1) >>> p(1)
1 1
"""
>>> q(1)
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
"""
def f(a,b):
result = a not in b
return result
def g(a,b):
cdef int result
result = a not in b
return result
def h(b):
result = 2 not in b
return result
def j(b):
cdef int result
result = 2 not in b
return result
def k(a):
cdef int result = a not in [1,2,3,4]
return result
def m(int a):
cdef int result = a not in [1,2,3,4]
return result
def n(a):
cdef int result = a.lower() not in [u'a *',u'b *',u'c *',u'd *']
return result
def p(a):
cdef dict d = {u'a': 1, u'b': 2} cdef dict d = {u'a': 1, u'b': 2}
cdef int result = a not in d cdef int result = a not in d
return result return result
def q(a): def q(a):
"""
>>> q(1)
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
"""
cdef dict d = None cdef dict d = None
cdef int result = a not in d # should fail with a TypeError cdef int result = a not in d # should fail with a TypeError
return result return result
__doc__ = u""" a,b = 'a *','b *' # use non-interned strings
>>> a,b = 'a *','b *' # use non-interned strings
>>> or2_assign(2,3) == (2 or 3)
True
>>> or2_assign('a', 'b') == ('a' or 'b')
True
>>> or2_assign(a, b) == (a or b)
True
>>> or2(2,3) == (2 or 3)
True
>>> or2(0,2) == (0 or 2)
True
>>> or2('a', 'b') == ('a' or 'b')
True
>>> or2(a, b) == (a or b)
True
>>> or2('', 'b') == ('' or 'b')
True
>>> or2([], [1]) == ([] or [1])
True
>>> or2([], [a]) == ([] or [a])
True
>>> or3(0,1,2) == (0 or 1 or 2)
True
>>> or3([],(),[1]) == ([] or () or [1])
True
>>> or2_no_result(2,3)
>>> or2_no_result(0,2)
>>> or2_no_result('a','b')
>>> or2_no_result(a,b)
>>> a or b
'a *'
"""
def or2_assign(a,b): def or2_assign(a,b):
"""
>>> or2_assign(2,3) == (2 or 3)
True
>>> or2_assign('a', 'b') == ('a' or 'b')
True
>>> or2_assign(a, b) == (a or b)
True
"""
c = a or b c = a or b
return c return c
def or2(a,b): def or2(a,b):
"""
>>> or2(2,3) == (2 or 3)
True
>>> or2(0,2) == (0 or 2)
True
>>> or2('a', 'b') == ('a' or 'b')
True
>>> or2(a, b) == (a or b)
True
>>> or2('', 'b') == ('' or 'b')
True
>>> or2([], [1]) == ([] or [1])
True
>>> or2([], [a]) == ([] or [a])
True
"""
return a or b return a or b
def or3(a,b,c): def or3(a,b,c):
"""
>>> or3(0,1,2) == (0 or 1 or 2)
True
>>> or3([],(),[1]) == ([] or () or [1])
True
"""
d = a or b or c d = a or b or c
return d return d
def or2_no_result(a,b): def or2_no_result(a,b):
"""
>>> or2_no_result(2,3)
>>> or2_no_result(0,2)
>>> or2_no_result('a','b')
>>> or2_no_result(a,b)
>>> a or b
'a *'
"""
a or b a or b
...@@ -13,4 +13,3 @@ ctypedef packed struct MyCTypeDefStruct: ...@@ -13,4 +13,3 @@ ctypedef packed struct MyCTypeDefStruct:
def f(): def f():
return (sizeof(MyCdefStruct), sizeof(MyCTypeDefStruct)) return (sizeof(MyCdefStruct), sizeof(MyCTypeDefStruct))
cimport cython cimport cython
@cython.test_assert_path_exists( @cython.test_assert_path_exists(
......
__doc__ = u"""
>>> f()
"""
def f(): def f():
"""
>>> f()
"""
pass pass
__doc__ = u"""
>>> test()
1
"""
cdef class Tri: cdef class Tri:
def test(self): def test(self):
return 1 return 1
...@@ -16,6 +11,10 @@ cdef produire_fiches(Tri tri): ...@@ -16,6 +11,10 @@ cdef produire_fiches(Tri tri):
return tri.test() return tri.test()
def test(): def test():
"""
>>> test()
1
"""
cdef Curseur c cdef Curseur c
c = Curseur() c = Curseur()
c.tri = Tri() c.tri = Tri()
......
__doc__ = u""" def f(obj2, obj3):
"""
>>> f(1.0, 2.95)[0] == f(1.0, 2.95)[1] >>> f(1.0, 2.95)[0] == f(1.0, 2.95)[1]
True True
"""
>>> g(4)
1024
>>> h(4)
625
>>> constant_py() == 2 ** 10
True
>>> constant_long() == 2 ** 36
True
>>> small_int_pow(3)
(1, 3, 9, 27, 81)
>>> small_int_pow(-5)
(1, -5, 25, -125, 625)
>>> int_pow(7, 2)
49
>>> int_pow(5, 3)
125
>>> int_pow(2, 10)
1024
"""
def f(obj2, obj3):
cdef float flt1, flt2, flt3 cdef float flt1, flt2, flt3
flt2, flt3 = obj2, obj3 flt2, flt3 = obj2, obj3
...@@ -36,21 +11,51 @@ def f(obj2, obj3): ...@@ -36,21 +11,51 @@ def f(obj2, obj3):
return flt1, obj1 return flt1, obj1
def g(i): def g(i):
"""
>>> g(4)
1024
"""
return i ** 5 return i ** 5
def h(i): def h(i):
"""
>>> h(4)
625
"""
return 5 ** i return 5 ** i
def constant_py(): def constant_py():
"""
>>> constant_py() == 2 ** 10
True
"""
result = (<object>2) ** 10 result = (<object>2) ** 10
return result return result
def constant_long(): def constant_long():
"""
>>> constant_long() == 2 ** 36
True
"""
result = (<object>2L) ** 36 result = (<object>2L) ** 36
return result return result
def small_int_pow(long s): def small_int_pow(long s):
"""
>>> small_int_pow(3)
(1, 3, 9, 27, 81)
>>> small_int_pow(-5)
(1, -5, 25, -125, 625)
"""
return s**0, s**1, s**2, s**3, s**4 return s**0, s**1, s**2, s**3, s**4
def int_pow(short a, short b): def int_pow(short a, short b):
"""
>>> int_pow(7, 2)
49
>>> int_pow(5, 3)
125
>>> int_pow(2, 10)
1024
"""
return a**b return a**b
__doc__ = u""" def f(a, b):
"""
>>> f(1, 'test') >>> f(1, 'test')
<BLANKLINE> <BLANKLINE>
1 1
1 test 1 test
1 test 1 test
1 test 42 spam 1 test 42 spam
""" """
def f(a, b):
print print
print a print a
print a, print a,
......
__doc__ = u"""
>>> test_sizeof()
True
True
True
True
True
>>> test_declare(100)
(100, 100)
>>> test_declare(100.5)
(100, 100)
>>> test_declare(None)
Traceback (most recent call last):
...
TypeError: an integer is required
>>> test_cast(1.5)
1
>>> test_cast(None)
Traceback (most recent call last):
...
TypeError: a float is required
>>> test_address(39)
39
>>> test_locals(5)
True
>>> test_struct(389, 1.64493)
(389, 1.64493)
>>> test_imports()
True
"""
import cython import cython
def test_sizeof(): def test_sizeof():
"""
>>> test_sizeof()
True
True
True
True
True
"""
x = cython.declare(cython.bint) x = cython.declare(cython.bint)
print sizeof(x) == sizeof(cython.bint) print sizeof(x) == sizeof(cython.bint)
print sizeof(cython.char) <= sizeof(cython.short) <= sizeof(cython.int) <= sizeof(cython.long) <= sizeof(cython.longlong) print sizeof(cython.char) <= sizeof(cython.short) <= sizeof(cython.int) <= sizeof(cython.long) <= sizeof(cython.longlong)
...@@ -49,6 +20,16 @@ def test_sizeof(): ...@@ -49,6 +20,16 @@ def test_sizeof():
print sizeof(cython.char) == 1 print sizeof(cython.char) == 1
def test_declare(n): def test_declare(n):
"""
>>> test_declare(100)
(100, 100)
>>> test_declare(100.5)
(100, 100)
>>> test_declare(None)
Traceback (most recent call last):
...
TypeError: an integer is required
"""
x = cython.declare(cython.int) x = cython.declare(cython.int)
y = cython.declare(cython.int, n) y = cython.declare(cython.int, n)
if cython.compiled: if cython.compiled:
...@@ -59,17 +40,33 @@ def test_declare(n): ...@@ -59,17 +40,33 @@ def test_declare(n):
@cython.locals(x=cython.double, n=cython.int) @cython.locals(x=cython.double, n=cython.int)
def test_cast(x): def test_cast(x):
"""
>>> test_cast(1.5)
1
>>> test_cast(None)
Traceback (most recent call last):
...
TypeError: a float is required
"""
n = cython.cast(cython.int, x) n = cython.cast(cython.int, x)
return n return n
@cython.locals(x=cython.int, y=cython.p_int) @cython.locals(x=cython.int, y=cython.p_int)
def test_address(x): def test_address(x):
"""
>>> test_address(39)
39
"""
y = cython.address(x) y = cython.address(x)
return y[0] return y[0]
@cython.locals(x=cython.int) @cython.locals(x=cython.int)
@cython.locals(y=cython.bint) @cython.locals(y=cython.bint)
def test_locals(x): def test_locals(x):
"""
>>> test_locals(5)
True
"""
y = x y = x
return y return y
...@@ -79,6 +76,10 @@ MyStruct = cython.struct(is_integral=cython.bint, data=MyUnion) ...@@ -79,6 +76,10 @@ MyStruct = cython.struct(is_integral=cython.bint, data=MyUnion)
MyStruct2 = cython.typedef(MyStruct[2]) MyStruct2 = cython.typedef(MyStruct[2])
def test_struct(n, x): def test_struct(n, x):
"""
>>> test_struct(389, 1.64493)
(389, 1.64493)
"""
a = cython.declare(MyStruct2) a = cython.declare(MyStruct2)
a[0] = MyStruct(True, data=MyUnion(n=n)) a[0] = MyStruct(True, data=MyUnion(n=n))
a[1] = MyStruct(is_integral=False, data={'x': x}) a[1] = MyStruct(is_integral=False, data={'x': x})
...@@ -90,6 +91,10 @@ from cython import declare as my_declare, locals as my_locals, p_void as my_void ...@@ -90,6 +91,10 @@ from cython import declare as my_declare, locals as my_locals, p_void as my_void
@my_locals(a=cython.p_void) @my_locals(a=cython.p_void)
def test_imports(): def test_imports():
"""
>>> test_imports()
True
"""
a = cython.NULL a = cython.NULL
b = declare(p_void, cython.NULL) b = declare(p_void, cython.NULL)
c = my_declare(my_void_star, cython.NULL) c = my_declare(my_void_star, cython.NULL)
......
__doc__ = u"""
>>> f()
>>> g()
"""
def f(): def f():
"""
>>> f()
"""
cdef int bool, int1, int2 cdef int bool, int1, int2
cdef object obj1, obj2 cdef object obj1, obj2
int1 = 0 int1 = 0
...@@ -22,6 +20,9 @@ def f(): ...@@ -22,6 +20,9 @@ def f():
assert bool assert bool
def g(): def g():
"""
>>> g()
"""
cdef int bool cdef int bool
obj1 = 1 obj1 = 1
obj2 = [] obj2 = []
...@@ -29,4 +30,3 @@ def g(): ...@@ -29,4 +30,3 @@ def g():
assert not bool assert not bool
bool = obj1 not in obj2 bool = obj1 not in obj2
assert bool assert bool
__doc__ = u""" def f(obj1, obj2, obj3):
"""
>>> f(1,2,3) >>> f(1,2,3)
3 3
>>> g(1,2,3) """
1
>>> h(1,2,3)
2
>>> j(1,2,3)
16
>>> k(1,2,3)
0
>>> l(1,2,3)
16
"""
def f(obj1, obj2, obj3):
obj1 = obj2 | obj3 obj1 = obj2 | obj3
return obj1 return obj1
def g(obj1, obj2, obj3): def g(obj1, obj2, obj3):
"""
>>> g(1,2,3)
1
"""
obj1 = obj2 ^ obj3 obj1 = obj2 ^ obj3
return obj1 return obj1
def h(obj1, obj2, obj3): def h(obj1, obj2, obj3):
"""
>>> h(1,2,3)
2
"""
obj1 = obj2 & obj3 obj1 = obj2 & obj3
return obj1 return obj1
def j(obj1, obj2, obj3): def j(obj1, obj2, obj3):
"""
>>> j(1,2,3)
16
"""
obj1 = obj2 << obj3 obj1 = obj2 << obj3
return obj1 return obj1
def k(obj1, obj2, obj3): def k(obj1, obj2, obj3):
"""
>>> k(1,2,3)
0
"""
obj1 = obj2 >> obj3 obj1 = obj2 >> obj3
return obj1 return obj1
def l(obj1, obj2, obj3): def l(obj1, obj2, obj3):
"""
>>> l(1,2,3)
16
"""
obj1 = obj2 << obj3 | obj2 >> obj3 obj1 = obj2 << obj3 | obj2 >> obj3
return obj1 return obj1
__doc__ = u""" def f():
"""
>>> f() >>> f()
6 6
>>> g() """
2
"""
def f():
obj1 = 1 obj1 = 1
obj2 = 2 obj2 = 2
obj3 = 3 obj3 = 3
...@@ -13,6 +10,10 @@ def f(): ...@@ -13,6 +10,10 @@ def f():
return obj1 return obj1
def g(): def g():
"""
>>> g()
2
"""
obj1 = 12 obj1 = 12
obj2 = 6 obj2 = 6
obj3 = 3 obj3 = 3
......
...@@ -18,4 +18,3 @@ def f(): ...@@ -18,4 +18,3 @@ def f():
p1 = <void*>a p1 = <void*>a
p2 = <PyObject*>a p2 = <PyObject*>a
return (<object>p1, <object>p2) return (<object>p1, <object>p2)
__doc__ = u"""
>>> swallow(name = "Brian")
This swallow is called Brian
>>> swallow(airspeed = 42)
This swallow is flying at 42 furlongs per fortnight
>>> swallow(coconuts = 3)
This swallow is carrying 3 coconuts
"""
def swallow(name = None, airspeed = None, coconuts = None): def swallow(name = None, airspeed = None, coconuts = None):
"""
>>> swallow(name = "Brian")
This swallow is called Brian
>>> swallow(airspeed = 42)
This swallow is flying at 42 furlongs per fortnight
>>> swallow(coconuts = 3)
This swallow is carrying 3 coconuts
"""
if name is not None: if name is not None:
print u"This swallow is called", name print u"This swallow is called", name
if airspeed is not None: if airspeed is not None:
print u"This swallow is flying at", airspeed, u"furlongs per fortnight" print u"This swallow is flying at", airspeed, u"furlongs per fortnight"
if coconuts is not None: if coconuts is not None:
print u"This swallow is carrying", coconuts, u"coconuts" print u"This swallow is carrying", coconuts, u"coconuts"
__doc__ = u"""
>>> f(100)
101L
>>> g(3000000000)
3000000001L
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u"L", u"") __doc__ = __doc__.replace(u"L", u"")
def f(x): def f(x):
"""
>>> f(100)
101L
"""
cdef unsigned long long ull cdef unsigned long long ull
ull = x ull = x
return ull + 1 return ull + 1
def g(unsigned long x): def g(unsigned long x):
"""
>>> g(3000000000)
3000000001L
"""
return x + 1 return x + 1
...@@ -15,4 +15,3 @@ cdef class eggs: ...@@ -15,4 +15,3 @@ cdef class eggs:
def eat(self): def eat(self):
raise RuntimeError(u"I don't like that") raise RuntimeError(u"I don't like that")
__doc__ = u"""
>>> go_py()
Spam!
Spam!
Spam!
Spam!
>>> go_py_ret()
2
>>> go_c()
Spam!
Spam!
Spam!
Spam!
>>> go_c_int(1,5)
Spam!
Spam!
>>> go_c_enumerate()
True
True
True
True
>>> go_c_all()
Spam!
Spam!
Spam!
>>> go_c_all_exprs(1)
Spam!
>>> go_c_all_exprs(3)
Spam!
Spam!
>>> go_c_const_exprs()
Spam!
Spam!
>>> go_c_calc(2)
Spam!
Spam!
>>> go_c_ret()
2
>>> go_c_calc_ret(2)
6
>>> go_list()
Spam!
Spam!
Spam!
Spam!
>>> go_list_ret()
2
>>> go_tuple()
Spam!
Spam!
Spam!
Spam!
>>> go_tuple_ret()
2
>>> go_dict()
Spam!
Spam!
Spam!
Spam!
>>> go_dict_ret()
2
>>> global_result
6
"""
def go_py(): def go_py():
"""
>>> go_py()
Spam!
Spam!
Spam!
Spam!
"""
for i in range(4): for i in range(4):
print u"Spam!" print u"Spam!"
def go_py_ret(): def go_py_ret():
"""
>>> go_py_ret()
2
"""
for i in range(4): for i in range(4):
if i > 1: if i > 1:
return i return i
def go_c(): def go_c():
"""
>>> go_c()
Spam!
Spam!
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(4): for i in range(4):
print u"Spam!" print u"Spam!"
def go_c_enumerate(): def go_c_enumerate():
"""
>>> go_c_enumerate()
True
True
True
True
"""
cdef int i,k cdef int i,k
for i,k in enumerate(range(4)): for i,k in enumerate(range(4)):
print i == k print i == k
def go_c_int(int a, int b): def go_c_int(int a, int b):
"""
>>> go_c_int(1,5)
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(a,b,2): for i in range(a,b,2):
print u"Spam!" print u"Spam!"
def go_c_all(): def go_c_all():
"""
>>> go_c_all()
Spam!
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(8,2,-2): for i in range(8,2,-2):
print u"Spam!" print u"Spam!"
def go_c_all_exprs(x): def go_c_all_exprs(x):
"""
>>> go_c_all_exprs(1)
Spam!
>>> go_c_all_exprs(3)
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(4*x,2*x,-3): for i in range(4*x,2*x,-3):
print u"Spam!" print u"Spam!"
def go_c_const_exprs(): def go_c_const_exprs():
"""
>>> go_c_const_exprs()
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(4*2+1,2*2,-2-1): for i in range(4*2+1,2*2,-2-1):
print u"Spam!" print u"Spam!"
...@@ -111,50 +89,98 @@ def f(x): ...@@ -111,50 +89,98 @@ def f(x):
return 2*x return 2*x
def go_c_calc(x): def go_c_calc(x):
"""
>>> go_c_calc(2)
Spam!
Spam!
"""
cdef int i cdef int i
for i in range(2*f(x),f(x), -2): for i in range(2*f(x),f(x), -2):
print u"Spam!" print u"Spam!"
def go_c_calc_ret(x): def go_c_calc_ret(x):
"""
>>> go_c_calc_ret(2)
6
"""
cdef int i cdef int i
for i in range(2*f(x),f(x), -2): for i in range(2*f(x),f(x), -2):
if i < 2*f(x): if i < 2*f(x):
return i return i
def go_c_ret(): def go_c_ret():
"""
>>> go_c_ret()
2
"""
cdef int i cdef int i
for i in range(4): for i in range(4):
if i > 1: if i > 1:
return i return i
def go_list(): def go_list():
"""
>>> go_list()
Spam!
Spam!
Spam!
Spam!
"""
cdef list l = list(range(4)) cdef list l = list(range(4))
for i in l: for i in l:
print u"Spam!" print u"Spam!"
def go_list_ret(): def go_list_ret():
"""
>>> go_list_ret()
2
"""
cdef list l = list(range(4)) cdef list l = list(range(4))
for i in l: for i in l:
if i > 1: if i > 1:
return i return i
def go_tuple(): def go_tuple():
"""
>>> go_tuple()
Spam!
Spam!
Spam!
Spam!
"""
cdef tuple t = tuple(range(4)) cdef tuple t = tuple(range(4))
for i in t: for i in t:
print u"Spam!" print u"Spam!"
def go_tuple_ret(): def go_tuple_ret():
"""
>>> go_tuple_ret()
2
"""
cdef tuple t = tuple(range(4)) cdef tuple t = tuple(range(4))
for i in t: for i in t:
if i > 1: if i > 1:
return i return i
def go_dict(): def go_dict():
"""
>>> go_dict()
Spam!
Spam!
Spam!
Spam!
"""
cdef dict d = dict(zip(range(4), range(4))) cdef dict d = dict(zip(range(4), range(4)))
for i in d: for i in d:
print u"Spam!" print u"Spam!"
def go_dict_ret(): def go_dict_ret():
"""
>>> go_dict_ret()
2
>>> global_result
6
"""
cdef dict d = dict(zip(range(4), range(4))) cdef dict d = dict(zip(range(4), range(4)))
for i in d: for i in d:
if i > 1 and i < 3: if i > 1 and i < 3:
......
__doc__ = u""" def blowup(p):
"""
>>> blowup([2, 3, 5]) >>> blowup([2, 3, 5])
1 1
""" """
def blowup(p):
cdef int n, i cdef int n, i
n = 10 n = 10
i = 1 i = 1
......
__doc__ = u""" def boolExpressionsFail():
"""
>>> boolExpressionsFail() >>> boolExpressionsFail()
'Not 2b' 'Not 2b'
""" """
def boolExpressionsFail():
dict = {1: 1} dict = {1: 1}
if not "2b" in dict: if not "2b" in dict:
return "Not 2b" return "Not 2b"
......
__doc__ = u""" def primes(int kmax):
"""
>>> primes(20) >>> primes(20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
""" """
def primes(int kmax):
cdef int n, k, i cdef int n, k, i
cdef int p[1000] cdef int p[1000]
result = [] result = []
......
__doc__ = u"""
>>> frighten()
NOBODY expects the Spanish Inquisition!
"""
def frighten(): def frighten():
"""
>>> frighten()
NOBODY expects the Spanish Inquisition!
"""
print u"NOBODY", u"expects", u"the Spanish Inquisition!" print u"NOBODY", u"expects", u"the Spanish Inquisition!"
__doc__ = u"""
>>> order()
42 tons of spam!
"""
class Spam: class Spam:
def __init__(self, w): def __init__(self, w):
...@@ -12,5 +7,9 @@ class Spam: ...@@ -12,5 +7,9 @@ class Spam:
print self.weight, u"tons of spam!" print self.weight, u"tons of spam!"
def order(): def order():
"""
>>> order()
42 tons of spam!
"""
s = Spam(42) s = Spam(42)
s.serve() s.serve()
__doc__ = u"""
>>> eggs()
Args: 1 2 3
Args: buckle my shoe
"""
def spam(a, b, c): def spam(a, b, c):
print u"Args:", a, b, c print u"Args:", a, b, c
def eggs(): def eggs():
"""
>>> eggs()
Args: 1 2 3
Args: buckle my shoe
"""
spam(*(1,2,3)) spam(*(1,2,3))
spam(*[u"buckle",u"my",u"shoe"]) spam(*[u"buckle",u"my",u"shoe"])
__doc__ = u""" def swallow(name, airspeed, *args, **kwds):
"""
>>> swallow("Brian", 42) >>> swallow("Brian", 42)
Name: Brian Name: Brian
Airspeed: 42 Airspeed: 42
Extra args: () Extra args: ()
Extra keywords: {} Extra keywords: {}
>>> swallow("Brian", 42, "African") >>> swallow("Brian", 42, "African")
Name: Brian Name: Brian
Airspeed: 42 Airspeed: 42
Extra args: ('African',) Extra args: ('African',)
Extra keywords: {} Extra keywords: {}
>>> swallow("Brian", airspeed = 42) >>> swallow("Brian", airspeed = 42)
Name: Brian Name: Brian
Airspeed: 42 Airspeed: 42
Extra args: () Extra args: ()
Extra keywords: {} Extra keywords: {}
>>> swallow("Brian", airspeed = 42, species = "African", coconuts = 3) >>> swallow("Brian", airspeed = 42, species = "African", coconuts = 3)
Name: Brian Name: Brian
Airspeed: 42 Airspeed: 42
Extra args: () Extra args: ()
Extra keywords: {'coconuts': 3, 'species': 'African'} Extra keywords: {'coconuts': 3, 'species': 'African'}
>>> swallow("Brian", 42, "African", coconuts = 3) >>> swallow("Brian", 42, "African", coconuts = 3)
Name: Brian Name: Brian
Airspeed: 42 Airspeed: 42
Extra args: ('African',) Extra args: ('African',)
Extra keywords: {'coconuts': 3} Extra keywords: {'coconuts': 3}
""" """
def swallow(name, airspeed, *args, **kwds):
print u"Name:", name print u"Name:", name
print u"Airspeed:", airspeed print u"Airspeed:", airspeed
print u"Extra args:", args print u"Extra args:", args
print u"Extra keywords:", kwds print u"Extra keywords:", kwds
__doc__ = u""" def spam(*args):
"""
>>> spam() >>> spam()
Args: () Args: ()
>>> spam(42) >>> spam(42)
Args: (42,) Args: (42,)
>>> spam("one", 2, "buckle my shoe") >>> spam("one", 2, "buckle my shoe")
Args: ('one', 2, 'buckle my shoe') Args: ('one', 2, 'buckle my shoe')
""" """
def spam(*args):
print u"Args:", args print u"Args:", args
__doc__ = u"""
>>> call_method( ExtType() ).method()
1
"""
cdef class ExtType: cdef class ExtType:
cdef c_method(self): cdef c_method(self):
return self return self
...@@ -11,4 +6,8 @@ cdef class ExtType: ...@@ -11,4 +6,8 @@ cdef class ExtType:
return 1 return 1
def call_method(ExtType et): def call_method(ExtType et):
"""
>>> call_method( ExtType() ).method()
1
"""
return <ExtType>et.c_method() return <ExtType>et.c_method()
import sys import sys
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
__doc__ = u""" __doc__ = u"""
......
__doc__ = u"""
>>> for_from_range(5, 10)
range(5)
at 0
at 1
at 2
at 3
at 4
range(5, 10)
at 5
at 6
at 7
at 8
at 9
range(5, 10, 2)
at 5
at 7
at 9
9
>>> for_from_range(-5, -10)
range(-5)
range(-5, -10)
range(-5, -10, 2)
100
>>> for_from_bound_reassignment(5, 1)
at 0
at 1
at 2
at 3
at 4
5
>>> for_from_step_reassignment(15, 5, 2)
at 0
at 5
at 10
15
>>> for_from_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
>>> for_from_py_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
>>> for_from_py_global_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
>>> for_in_target_reassignment(10, 2)
at 0
at 1
at 2
at 3
at 4
at 5
at 6
at 7
at 8
at 9
18
>>> test_func(5)
get_bound(5)
at 0
at 1
at 2
at 3
at 4
5
"""
cdef int get_bound(int m): cdef int get_bound(int m):
print u"get_bound(%s)"%m print u"get_bound(%s)"%m
return m return m
def for_from_range(a, b): def for_from_range(a, b):
"""
>>> for_from_range(5, 10)
range(5)
at 0
at 1
at 2
at 3
at 4
range(5, 10)
at 5
at 6
at 7
at 8
at 9
range(5, 10, 2)
at 5
at 7
at 9
9
>>> for_from_range(-5, -10)
range(-5)
range(-5, -10)
range(-5, -10, 2)
100
"""
cdef int i = 100 cdef int i = 100
print u"range(%s)" % a print u"range(%s)" % a
for i in range(a): for i in range(a):
...@@ -91,6 +41,15 @@ def for_from_range(a, b): ...@@ -91,6 +41,15 @@ def for_from_range(a, b):
return i return i
def for_from_bound_reassignment(int bound, int fake_bound): def for_from_bound_reassignment(int bound, int fake_bound):
"""
>>> for_from_bound_reassignment(5, 1)
at 0
at 1
at 2
at 3
at 4
5
"""
cdef int i = 100 cdef int i = 100
for i from 0 <= i < bound: for i from 0 <= i < bound:
print u"at", i print u"at", i
...@@ -98,6 +57,13 @@ def for_from_bound_reassignment(int bound, int fake_bound): ...@@ -98,6 +57,13 @@ def for_from_bound_reassignment(int bound, int fake_bound):
return i return i
def for_from_step_reassignment(int bound, int step, int fake_step): def for_from_step_reassignment(int bound, int step, int fake_step):
"""
>>> for_from_step_reassignment(15, 5, 2)
at 0
at 5
at 10
15
"""
cdef int i = 100 cdef int i = 100
for i from 0 <= i < bound by step: for i from 0 <= i < bound by step:
print u"at", i print u"at", i
...@@ -105,6 +71,14 @@ def for_from_step_reassignment(int bound, int step, int fake_step): ...@@ -105,6 +71,14 @@ def for_from_step_reassignment(int bound, int step, int fake_step):
return i return i
def for_from_target_reassignment(int bound, int factor): def for_from_target_reassignment(int bound, int factor):
"""
>>> for_from_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
"""
cdef int i = 100 cdef int i = 100
for i from 0 <= i < bound: for i from 0 <= i < bound:
print u"at", i print u"at", i
...@@ -112,6 +86,14 @@ def for_from_target_reassignment(int bound, int factor): ...@@ -112,6 +86,14 @@ def for_from_target_reassignment(int bound, int factor):
return i return i
def for_from_py_target_reassignment(int bound, int factor): def for_from_py_target_reassignment(int bound, int factor):
"""
>>> for_from_py_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
"""
cdef object i cdef object i
for i from 0 <= i < bound: for i from 0 <= i < bound:
print u"at", i print u"at", i
...@@ -119,6 +101,14 @@ def for_from_py_target_reassignment(int bound, int factor): ...@@ -119,6 +101,14 @@ def for_from_py_target_reassignment(int bound, int factor):
return i return i
def for_from_py_global_target_reassignment(int bound, int factor): def for_from_py_global_target_reassignment(int bound, int factor):
"""
>>> for_from_py_global_target_reassignment(10, 2)
at 0
at 1
at 3
at 7
15
"""
global g_var global g_var
for g_var from 0 <= g_var < bound: for g_var from 0 <= g_var < bound:
print u"at", g_var print u"at", g_var
...@@ -126,6 +116,20 @@ def for_from_py_global_target_reassignment(int bound, int factor): ...@@ -126,6 +116,20 @@ def for_from_py_global_target_reassignment(int bound, int factor):
return g_var return g_var
def for_in_target_reassignment(int bound, int factor): def for_in_target_reassignment(int bound, int factor):
"""
>>> for_in_target_reassignment(10, 2)
at 0
at 1
at 2
at 3
at 4
at 5
at 6
at 7
at 8
at 9
18
"""
cdef int i = 100 cdef int i = 100
for i in range(bound): for i in range(bound):
print u"at", i print u"at", i
...@@ -133,6 +137,16 @@ def for_in_target_reassignment(int bound, int factor): ...@@ -133,6 +137,16 @@ def for_in_target_reassignment(int bound, int factor):
return i return i
def test_func(int n): def test_func(int n):
"""
>>> test_func(5)
get_bound(5)
at 0
at 1
at 2
at 3
at 4
5
"""
cdef int i = 100 cdef int i = 100
for i from 0 <= i < get_bound(n): for i from 0 <= i < get_bound(n):
print u"at", i print u"at", i
......
__doc__ = u""" def f():
"""
>>> f() >>> f()
42 42
""" """
def f():
a = 42 a = 42
b = a b = a
return b return b
__doc__ = u"""
>>> f('test')
>>> test_g()
>>> test_h(5)
5
"""
def f(a): def f(a):
"""
>>> f('test')
"""
return return
return a return a
return 42 return 42
...@@ -19,7 +15,14 @@ cdef int h(a): ...@@ -19,7 +15,14 @@ cdef int h(a):
return i return i
def test_g(): def test_g():
"""
>>> test_g()
"""
g() g()
def test_h(i): def test_h(i):
"""
>>> test_h(5)
5
"""
return h(i) return h(i)
__doc__ = u"""
>>> test()
5
"""
def test(): def test():
"""
>>> test()
5
"""
a = b = c = 5 a = b = c = 5
return a return a
__doc__ = u""" __doc__ = """
>>> z(1,9.2, b'test') >>> z(1,9.2, b'test')
>>> failtype()
Traceback (most recent call last):
TypeError: an integer is required
>>> fail0(1,2)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (0 given)
>>> fail1(1,2)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (1 given)
""" """
import sys import sys
...@@ -33,10 +22,25 @@ def z(a, b, c): ...@@ -33,10 +22,25 @@ def z(a, b, c):
g(a, b, c) g(a, b, c)
def fail0(a, b): def fail0(a, b):
"""
>>> fail0(1,2)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (0 given)
"""
f() f()
def fail1(a, b): def fail1(a, b):
"""
>>> fail1(1,2)
Traceback (most recent call last):
TypeError: f() takes exactly 2 positional arguments (1 given)
"""
f(a) f(a)
def failtype(): def failtype():
"""
>>> failtype()
Traceback (most recent call last):
TypeError: an integer is required
"""
h(42, "eggs") h(42, "eggs")
__doc__ = u"""
>>> f()
"""
cdef struct Spam: cdef struct Spam:
char *grail char *grail
def f(): def f():
"""
>>> f()
"""
cdef int i, j, k cdef int i, j, k
cdef char *p cdef char *p
i = sizeof(p) i = sizeof(p)
......
__doc__ = u""" def f(obj1, obj2, obj3, obj4):
"""
>>> l = [1,2,3,4] >>> l = [1,2,3,4]
>>> f(1, l, 2, 3) >>> f(1, l, 2, 3)
[1, 2, 3, 4] [1, 2, 3, 4]
>>> l == f(1, l, 2, 3) >>> l == f(1, l, 2, 3)
True True
>>> l is f(1, l, 2, 3) >>> l is f(1, l, 2, 3)
False False
"""
>>> g(1, [1,2,3,4], 2, 3)
[3, 4]
>>> h(1, [1,2,3,4], 2, 3)
[1, 2, 3]
>>> j(1, [1,2,3,4], 2, 3)
[3]
>>> slice_of_temporary_smoketest()
[3, 2]
"""
def f(obj1, obj2, obj3, obj4):
obj1 = obj2[:] obj1 = obj2[:]
return obj1 return obj1
def g(obj1, obj2, obj3, obj4): def g(obj1, obj2, obj3, obj4):
"""
>>> g(1, [1,2,3,4], 2, 3)
[3, 4]
"""
obj1 = obj2[obj3:] obj1 = obj2[obj3:]
return obj1 return obj1
def h(obj1, obj2, obj3, obj4): def h(obj1, obj2, obj3, obj4):
"""
>>> h(1, [1,2,3,4], 2, 3)
[1, 2, 3]
"""
obj1 = obj2[:obj4] obj1 = obj2[:obj4]
return obj1 return obj1
def j(obj1, obj2, obj3, obj4): def j(obj1, obj2, obj3, obj4):
"""
>>> j(1, [1,2,3,4], 2, 3)
[3]
"""
obj1 = obj2[obj3:obj4] obj1 = obj2[obj3:obj4]
return obj1 return obj1
...@@ -41,6 +39,10 @@ class A(object): ...@@ -41,6 +39,10 @@ class A(object):
pass pass
def slice_of_temporary_smoketest(): def slice_of_temporary_smoketest():
"""
>>> slice_of_temporary_smoketest()
[3, 2]
"""
x = A() x = A()
x.a = [1, 2] x.a = [1, 2]
x.a[:] = [3,2] x.a[:] = [3,2]
......
__doc__ = u"""
>>> f()
12.5
>>> nan1()
nan
>>> nan2()
nan
>>> nan3()
nan
>>> float_nan
nan
>>> infp1()
inf
>>> infp1() == float('inf')
True
>>> infp2()
inf
>>> infp2() == float('inf')
True
>>> infp3()
inf
>>> infp3() == float('inf')
True
>>> float_infp
inf
>>> float_infp == float('inf')
True
>>> infn1()
-inf
>>> infn1() == float('-inf')
True
>>> infn2()
-inf
>>> infn2() == float('-inf')
True
>>> infn3()
-inf
>>> infn3() == float('-inf')
True
>>> float_infn
-inf
>>> float_infn == float('-inf')
True
>>> global_floats()[1:] == (float('+inf'), float('-inf'))
True
>>> global_floats()[0]
nan
"""
DEF FLOAT = 12.5 DEF FLOAT = 12.5
DEF FLOAT_NAN = float('nan') DEF FLOAT_NAN = float('nan')
DEF FLOAT_INFP = float('+inf') DEF FLOAT_INFP = float('+inf')
...@@ -65,54 +12,122 @@ float_infp = FLOAT_INFP ...@@ -65,54 +12,122 @@ float_infp = FLOAT_INFP
float_infn = FLOAT_INFN float_infn = FLOAT_INFN
def f(): def f():
"""
>>> f()
12.5
"""
cdef float f cdef float f
f = FLOAT f = FLOAT
return f return f
def nan1(): def nan1():
"""
>>> nan1()
nan
"""
cdef double f cdef double f
f = FLOAT_NAN f = FLOAT_NAN
return f return f
def nan2(): def nan2():
"""
>>> nan2()
nan
"""
cdef double f cdef double f
f = float('nan') f = float('nan')
return f return f
def nan3(): def nan3():
"""
>>> nan3()
nan
>>> float_nan
nan
"""
cdef float f cdef float f
f = FLOAT_NAN f = FLOAT_NAN
return f return f
def infp1(): def infp1():
"""
>>> infp1()
inf
>>> infp1() == float('inf')
True
"""
cdef double f cdef double f
f = FLOAT_INFP f = FLOAT_INFP
return f return f
def infp2(): def infp2():
"""
>>> infp2()
inf
>>> infp2() == float('inf')
True
"""
cdef double f cdef double f
f = float('+inf') f = float('+inf')
return f return f
def infp3(): def infp3():
"""
>>> infp3()
inf
>>> infp3() == float('inf')
True
>>> float_infp
inf
>>> float_infp == float('inf')
True
"""
cdef float f cdef float f
f = FLOAT_INFP f = FLOAT_INFP
return f return f
def infn1(): def infn1():
"""
>>> infn1()
-inf
>>> infn1() == float('-inf')
True
"""
cdef double f cdef double f
f = FLOAT_INFN f = FLOAT_INFN
return f return f
def infn2(): def infn2():
"""
>>> infn2()
-inf
>>> infn2() == float('-inf')
True
"""
cdef double f cdef double f
f = float('-inf') f = float('-inf')
return f return f
def infn3(): def infn3():
"""
>>> infn3()
-inf
>>> infn3() == float('-inf')
True
>>> float_infn
-inf
>>> float_infn == float('-inf')
True
"""
cdef float f cdef float f
f = FLOAT_INFN f = FLOAT_INFN
return f return f
def global_floats(): def global_floats():
"""
>>> global_floats()[1:] == (float('+inf'), float('-inf'))
True
>>> global_floats()[0]
nan
"""
return (cdef_float_nan, cdef_float_infp, cdef_float_infn) return (cdef_float_nan, cdef_float_infp, cdef_float_infn)
__doc__ = u""" cdef sorteditems(d):
l = list(d.items())
l.sort()
return tuple(l)
def spam(x, y, z):
"""
>>> spam(1,2,3) >>> spam(1,2,3)
(1, 2, 3) (1, 2, 3)
>>> spam(1,2) >>> spam(1,2)
...@@ -10,7 +16,11 @@ __doc__ = u""" ...@@ -10,7 +16,11 @@ __doc__ = u"""
>>> spam(1,2,3, a=1) >>> spam(1,2,3, a=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: spam() got an unexpected keyword argument 'a' TypeError: spam() got an unexpected keyword argument 'a'
"""
return (x, y, z)
def grail(x, y, z, *a):
"""
>>> grail(1,2,3) >>> grail(1,2,3)
(1, 2, 3, ()) (1, 2, 3, ())
>>> grail(1,2,3,4) >>> grail(1,2,3,4)
...@@ -23,7 +33,11 @@ __doc__ = u""" ...@@ -23,7 +33,11 @@ __doc__ = u"""
>>> grail(1,2,3, a=1) >>> grail(1,2,3, a=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: grail() got an unexpected keyword argument 'a' TypeError: grail() got an unexpected keyword argument 'a'
"""
return (x, y, z, a)
def swallow(x, y, z, **k):
"""
>>> swallow(1,2,3) >>> swallow(1,2,3)
(1, 2, 3, ()) (1, 2, 3, ())
>>> swallow(1,2,3,4) >>> swallow(1,2,3,4)
...@@ -34,7 +48,11 @@ __doc__ = u""" ...@@ -34,7 +48,11 @@ __doc__ = u"""
>>> swallow(1,2,3, x=1) >>> swallow(1,2,3, x=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: swallow() got multiple values for keyword argument 'x' TypeError: swallow() got multiple values for keyword argument 'x'
"""
return (x, y, z, sorteditems(k))
def creosote(x, y, z, *a, **k):
"""
>>> creosote(1,2,3) >>> creosote(1,2,3)
(1, 2, 3, (), ()) (1, 2, 3, (), ())
>>> creosote(1,2,3,4) >>> creosote(1,2,3,4)
...@@ -46,7 +64,11 @@ __doc__ = u""" ...@@ -46,7 +64,11 @@ __doc__ = u"""
>>> creosote(1,2,3,4, x=1) >>> creosote(1,2,3,4, x=1)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: creosote() got multiple values for keyword argument 'x' TypeError: creosote() got multiple values for keyword argument 'x'
"""
return (x, y, z, a, sorteditems(k))
def onlyt(*a):
"""
>>> onlyt(1) >>> onlyt(1)
(1,) (1,)
>>> onlyt(1,2) >>> onlyt(1,2)
...@@ -57,7 +79,11 @@ __doc__ = u""" ...@@ -57,7 +79,11 @@ __doc__ = u"""
>>> onlyt(1, a=2) >>> onlyt(1, a=2)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: onlyt() got an unexpected keyword argument 'a' TypeError: onlyt() got an unexpected keyword argument 'a'
"""
return a
def onlyk(**k):
"""
>>> onlyk(a=1) >>> onlyk(a=1)
(('a', 1),) (('a', 1),)
>>> onlyk(a=1, b=2) >>> onlyk(a=1, b=2)
...@@ -71,7 +97,11 @@ __doc__ = u""" ...@@ -71,7 +97,11 @@ __doc__ = u"""
>>> onlyk(1, a=1, b=2) >>> onlyk(1, a=1, b=2)
Traceback (most recent call last): Traceback (most recent call last):
TypeError: onlyk() takes exactly 0 positional arguments (1 given) TypeError: onlyk() takes exactly 0 positional arguments (1 given)
"""
return sorteditems(k)
def tk(*a, **k):
"""
>>> tk(a=1) >>> tk(a=1)
(('a', 1),) (('a', 1),)
>>> tk(a=1, b=2) >>> tk(a=1, b=2)
...@@ -82,30 +112,5 @@ __doc__ = u""" ...@@ -82,30 +112,5 @@ __doc__ = u"""
(1, 2) (1, 2)
>>> tk(1, a=1, b=2) >>> tk(1, a=1, b=2)
(1, ('a', 1), ('b', 2)) (1, ('a', 1), ('b', 2))
""" """
cdef sorteditems(d):
l = list(d.items())
l.sort()
return tuple(l)
def spam(x, y, z):
return (x, y, z)
def grail(x, y, z, *a):
return (x, y, z, a)
def swallow(x, y, z, **k):
return (x, y, z, sorteditems(k))
def creosote(x, y, z, *a, **k):
return (x, y, z, a, sorteditems(k))
def onlyt(*a):
return a
def onlyk(**k):
return sorteditems(k)
def tk(*a, **k):
return a + sorteditems(k) return a + sorteditems(k)
__doc__ = u"""
>>> test_eq()
True
True
True
True
>>> test_cascaded_eq()
True
True
True
True
True
True
True
True
>>> test_cascaded_ineq()
True
True
True
True
True
True
True
True
>>> test_long_ineq()
True
>>> test_long_ineq_py()
True
True
"""
cdef int i = 'x' cdef int i = 'x'
cdef char c = 'x' cdef char c = 'x'
cdef char* s = 'x' cdef char* s = 'x'
def test_eq(): def test_eq():
"""
>>> test_eq()
True
True
True
True
"""
print i == 'x' print i == 'x'
print i == c'x' print i == c'x'
print c == 'x' print c == 'x'
...@@ -46,6 +18,17 @@ def test_eq(): ...@@ -46,6 +18,17 @@ def test_eq():
# print s == c'x' # error # print s == c'x' # error
def test_cascaded_eq(): def test_cascaded_eq():
"""
>>> test_cascaded_eq()
True
True
True
True
True
True
True
True
"""
print 'x' == i == 'x' print 'x' == i == 'x'
print 'x' == i == c'x' print 'x' == i == c'x'
print c'x' == i == 'x' print c'x' == i == 'x'
...@@ -57,6 +40,17 @@ def test_cascaded_eq(): ...@@ -57,6 +40,17 @@ def test_cascaded_eq():
print c'x' == c == c'x' print c'x' == c == c'x'
def test_cascaded_ineq(): def test_cascaded_ineq():
"""
>>> test_cascaded_ineq()
True
True
True
True
True
True
True
True
"""
print 'a' <= i <= 'z' print 'a' <= i <= 'z'
print 'a' <= i <= c'z' print 'a' <= i <= c'z'
print c'a' <= i <= 'z' print c'a' <= i <= 'z'
...@@ -68,8 +62,17 @@ def test_cascaded_ineq(): ...@@ -68,8 +62,17 @@ def test_cascaded_ineq():
print c'a' <= c <= c'z' print c'a' <= c <= c'z'
def test_long_ineq(): def test_long_ineq():
"""
>>> test_long_ineq()
True
"""
print 'a' < 'b' < 'c' < 'd' < c < 'y' < 'z' print 'a' < 'b' < 'c' < 'd' < c < 'y' < 'z'
def test_long_ineq_py(): def test_long_ineq_py():
"""
>>> test_long_ineq_py()
True
True
"""
print 'abcdef' < 'b' < 'c' < 'd' < 'y' < 'z' print 'abcdef' < 'b' < 'c' < 'd' < 'y' < 'z'
print 'a' < 'b' < 'cde' < 'd' < 'y' < 'z' print 'a' < 'b' < 'cde' < 'd' < 'y' < 'z'
...@@ -6,4 +6,3 @@ __doc__ = u""" ...@@ -6,4 +6,3 @@ __doc__ = u"""
class C: class C:
x = "foo" x = "foo"
...@@ -3,29 +3,35 @@ __doc__ = u""" ...@@ -3,29 +3,35 @@ __doc__ = u"""
'test' 'test'
>>> z >>> z
'test' 'test'
>>> c('testing')
'testing'
>>> sub('testing a subtype')
'testing a subtype'
>>> subs('testing a subtype')
'testing a subtype'
# >>> csub('testing a subtype')
# 'testing a subtype'
# >>> csubs('testing a subtype')
# 'testing a subtype'
""" """
s = str s = str
z = str('test') z = str('test')
def c(string): def c(string):
"""
>>> c('testing')
'testing'
"""
return str(string) return str(string)
class subs(str): class subs(str):
"""
>>> subs('testing a subtype')
'testing a subtype'
# >>> csub('testing a subtype')
# 'testing a subtype'
# >>> csubs('testing a subtype')
# 'testing a subtype'
"""
pass pass
def sub(string): def sub(string):
"""
>>> sub('testing a subtype')
'testing a subtype'
"""
return subs(string) return subs(string)
#cdef class subs(str): #cdef class subs(str):
......
__doc__ = u""" cdef struct Point:
double x
double y
int color
def test_constructor(x, y, color):
"""
>>> test_constructor(1,2,255) >>> test_constructor(1,2,255)
{'y': 2.0, 'x': 1.0, 'color': 255} {'y': 2.0, 'x': 1.0, 'color': 255}
>>> test_constructor(1,None,255) >>> test_constructor(1,None,255)
Traceback (most recent call last): Traceback (most recent call last):
... ...
TypeError: a float is required TypeError: a float is required
"""
cdef Point p = Point(x, y, color)
return p
def test_constructor_kwds(x, y, color):
"""
>>> test_constructor_kwds(1.25, 2.5, 128) >>> test_constructor_kwds(1.25, 2.5, 128)
{'y': 2.5, 'x': 1.25, 'color': 128} {'y': 2.5, 'x': 1.25, 'color': 128}
>>> test_constructor_kwds(1.25, 2.5, None) >>> test_constructor_kwds(1.25, 2.5, None)
Traceback (most recent call last): Traceback (most recent call last):
... ...
TypeError: an integer is required TypeError: an integer is required
"""
cdef Point p = Point(x=x, y=y, color=color)
return p
def test_dict_construction(x, y, color):
"""
>>> test_dict_construction(4, 5, 64) >>> test_dict_construction(4, 5, 64)
{'y': 5.0, 'x': 4.0, 'color': 64} {'y': 5.0, 'x': 4.0, 'color': 64}
>>> test_dict_construction("foo", 5, 64) >>> test_dict_construction("foo", 5, 64)
Traceback (most recent call last): Traceback (most recent call last):
... ...
TypeError: a float is required TypeError: a float is required
"""
>>> test_pointers(100, 2.71828)
100
2.71828
True
"""
cdef struct Point:
double x
double y
int color
def test_constructor(x, y, color):
cdef Point p = Point(x, y, color)
return p
def test_constructor_kwds(x, y, color):
cdef Point p = Point(x=x, y=y, color=color)
return p
def test_dict_construction(x, y, color):
cdef Point p = {'color': color, 'x': x, 'y': y} cdef Point p = {'color': color, 'x': x, 'y': y}
return p return p
...@@ -53,6 +49,12 @@ cdef struct with_pointers: ...@@ -53,6 +49,12 @@ cdef struct with_pointers:
void* ptr void* ptr
def test_pointers(int n, double x): def test_pointers(int n, double x):
"""
>>> test_pointers(100, 2.71828)
100
2.71828
True
"""
cdef with_pointers a = [True, {'n': n}, NULL] cdef with_pointers a = [True, {'n': n}, NULL]
cdef with_pointers b = with_pointers(False, {'x': x}, NULL) cdef with_pointers b = with_pointers(False, {'x': x}, NULL)
print a.data.n print a.data.n
......
__doc__ = u"""
>>> zoo = Zoo()
>>> for cl in (Zoo, Bam, Bar, Foo, Base, Base0): assert isinstance(zoo, cl)
>>> fooit(zoo)
42
>>> bam = Bam()
>>> for cl in (Bam, Bar, Foo, Base, Base0): assert isinstance(bam, cl)
>>> fooit(bam)
42
>>> bar = Bar()
>>> for cl in (Bar, Foo, Base, Base0): assert isinstance(bar, cl)
>>> fooit(bar)
42
>>> foo = Foo()
>>> for cl in (Foo, Base, Base0): assert isinstance(foo, cl)
>>> fooit(foo)
42
>>> base = Base()
>>> for cl in (Base, Base0): assert isinstance(base, cl)
>>> fooit(base)
Traceback (most recent call last):
TypeError: Argument 'foo' has incorrect type (expected subclasses.Foo, got subclasses.Base)
>>> base0 = Base0()
>>> for cl in (Base0,): assert isinstance(base0, cl)
>>> fooit(base0)
Traceback (most recent call last):
TypeError: Argument 'foo' has incorrect type (expected subclasses.Foo, got subclasses.Base0)
"""
cdef class Base0: cdef class Base0:
pass pass
...@@ -53,4 +19,32 @@ cdef class Zoo(Bam): ...@@ -53,4 +19,32 @@ cdef class Zoo(Bam):
def fooit(Foo foo): def fooit(Foo foo):
"""
>>> zoo = Zoo()
>>> for cl in (Zoo, Bam, Bar, Foo, Base, Base0): assert isinstance(zoo, cl)
>>> fooit(zoo)
42
>>> bam = Bam()
>>> for cl in (Bam, Bar, Foo, Base, Base0): assert isinstance(bam, cl)
>>> fooit(bam)
42
>>> bar = Bar()
>>> for cl in (Bar, Foo, Base, Base0): assert isinstance(bar, cl)
>>> fooit(bar)
42
>>> foo = Foo()
>>> for cl in (Foo, Base, Base0): assert isinstance(foo, cl)
>>> fooit(foo)
42
>>> base = Base()
>>> for cl in (Base, Base0): assert isinstance(base, cl)
>>> fooit(base)
Traceback (most recent call last):
TypeError: Argument 'foo' has incorrect type (expected subclasses.Foo, got subclasses.Base)
>>> base0 = Base0()
>>> for cl in (Base0,): assert isinstance(base0, cl)
>>> fooit(base0)
Traceback (most recent call last):
TypeError: Argument 'foo' has incorrect type (expected subclasses.Foo, got subclasses.Base0)
"""
return foo.fooit() return foo.fooit()
__doc__ = u""" def f():
"""
>>> f() >>> f()
(-1, -1) (-1, -1)
>>> p() """
0
"""
def f():
cdef int int1, int2, int3 cdef int int1, int2, int3
obj1 = 1 obj1 = 1
obj2 = 2 obj2 = 2
...@@ -18,6 +15,10 @@ def f(): ...@@ -18,6 +15,10 @@ def f():
return int1, obj1 return int1, obj1
def p(): def p():
"""
>>> p()
0
"""
cdef int int1, int2, int3 cdef int int1, int2, int3
cdef char *ptr1, *ptr2, *ptr3 cdef char *ptr1, *ptr2, *ptr3
int2 = 2 int2 = 2
......
__doc__ = u"""
>>> switch_simple_py(1)
1
>>> switch_simple_py(2)
2
>>> switch_simple_py(3)
3
>>> switch_simple_py(4)
8
>>> switch_simple_py(5)
0
>>> switch_py(1)
1
>>> switch_py(2)
2
>>> switch_py(3)
3
>>> switch_py(4)
4
>>> switch_py(5)
4
>>> switch_py(6)
0
>>> switch_py(8)
4
>>> switch_py(10)
10
>>> switch_py(12)
12
>>> switch_py(13)
0
>>> switch_simple_c(1)
1
>>> switch_simple_c(2)
2
>>> switch_simple_c(3)
3
>>> switch_simple_c(4)
8
>>> switch_simple_c(5)
0
>>> switch_c(1)
1
>>> switch_c(2)
2
>>> switch_c(3)
3
>>> switch_c(4)
4
>>> switch_c(5)
4
>>> switch_c(6)
0
>>> switch_c(8)
4
>>> switch_c(10)
10
>>> switch_c(12)
12
>>> switch_c(13)
0
>>> switch_or(0)
0
>>> switch_or(1)
1
>>> switch_or(2)
1
>>> switch_or(3)
1
>>> switch_or(4)
0
>>> switch_in(0)
0
>>> switch_in(1)
1
>>> switch_in(2)
0
>>> switch_in(7)
1
>>> switch_in(8)
0
>>> switch_short(0)
0
>>> switch_short(1)
1
>>> switch_short(2)
2
>>> switch_short(3)
0
>>> switch_off(0)
0
>>> switch_off(1)
1
>>> switch_off(2)
0
>>> switch_pass(1)
1
"""
def switch_simple_py(x): def switch_simple_py(x):
"""
>>> switch_simple_py(1)
1
>>> switch_simple_py(2)
2
>>> switch_simple_py(3)
3
>>> switch_simple_py(4)
8
>>> switch_simple_py(5)
0
"""
if x == 1: if x == 1:
return 1 return 1
elif 2 == x: elif 2 == x:
...@@ -119,6 +24,28 @@ def switch_simple_py(x): ...@@ -119,6 +24,28 @@ def switch_simple_py(x):
return -1 return -1
def switch_py(x): def switch_py(x):
"""
>>> switch_py(1)
1
>>> switch_py(2)
2
>>> switch_py(3)
3
>>> switch_py(4)
4
>>> switch_py(5)
4
>>> switch_py(6)
0
>>> switch_py(8)
4
>>> switch_py(10)
10
>>> switch_py(12)
12
>>> switch_py(13)
0
"""
if x == 1: if x == 1:
return 1 return 1
elif 2 == x: elif 2 == x:
...@@ -136,6 +63,18 @@ def switch_py(x): ...@@ -136,6 +63,18 @@ def switch_py(x):
return -1 return -1
def switch_simple_c(int x): def switch_simple_c(int x):
"""
>>> switch_simple_c(1)
1
>>> switch_simple_c(2)
2
>>> switch_simple_c(3)
3
>>> switch_simple_c(4)
8
>>> switch_simple_c(5)
0
"""
if x == 1: if x == 1:
return 1 return 1
elif 2 == x: elif 2 == x:
...@@ -149,6 +88,28 @@ def switch_simple_c(int x): ...@@ -149,6 +88,28 @@ def switch_simple_c(int x):
return -1 return -1
def switch_c(int x): def switch_c(int x):
"""
>>> switch_c(1)
1
>>> switch_c(2)
2
>>> switch_c(3)
3
>>> switch_c(4)
4
>>> switch_c(5)
4
>>> switch_c(6)
0
>>> switch_c(8)
4
>>> switch_c(10)
10
>>> switch_c(12)
12
>>> switch_c(13)
0
"""
if x == 1: if x == 1:
return 1 return 1
elif 2 == x: elif 2 == x:
...@@ -166,6 +127,18 @@ def switch_c(int x): ...@@ -166,6 +127,18 @@ def switch_c(int x):
return -1 return -1
def switch_or(int x): def switch_or(int x):
"""
>>> switch_or(0)
0
>>> switch_or(1)
1
>>> switch_or(2)
1
>>> switch_or(3)
1
>>> switch_or(4)
0
"""
if x == 1 or x == 2 or x == 3: if x == 1 or x == 2 or x == 3:
return 1 return 1
else: else:
...@@ -173,11 +146,33 @@ def switch_or(int x): ...@@ -173,11 +146,33 @@ def switch_or(int x):
return -1 return -1
def switch_in(int X): def switch_in(int X):
"""
>>> switch_in(0)
0
>>> switch_in(1)
1
>>> switch_in(2)
0
>>> switch_in(7)
1
>>> switch_in(8)
0
"""
if X in (1,3,5,7): if X in (1,3,5,7):
return 1 return 1
return 0 return 0
def switch_short(int x): def switch_short(int x):
"""
>>> switch_short(0)
0
>>> switch_short(1)
1
>>> switch_short(2)
2
>>> switch_short(3)
0
"""
if x == 1: if x == 1:
return 1 return 1
elif 2 == x: elif 2 == x:
...@@ -187,6 +182,14 @@ def switch_short(int x): ...@@ -187,6 +182,14 @@ def switch_short(int x):
return -1 return -1
def switch_off(int x): def switch_off(int x):
"""
>>> switch_off(0)
0
>>> switch_off(1)
1
>>> switch_off(2)
0
"""
if x == 1: if x == 1:
return 1 return 1
else: else:
...@@ -194,6 +197,10 @@ def switch_off(int x): ...@@ -194,6 +197,10 @@ def switch_off(int x):
return -1 return -1
def switch_pass(int x): def switch_pass(int x):
"""
>>> switch_pass(1)
1
"""
if x == 1: if x == 1:
pass pass
elif x == 2: elif x == 2:
......
__doc__ = u"""
>>> result() == (99, 17*42, 17*42)
True
"""
cdef int i, j, k cdef int i, j, k
i = 17; j = 42; k = i * j i = 17; j = 42; k = i * j
if j > k: i = 88 if j > k: i = 88
else: i = 99; j = k else: i = 99; j = k
def result(): def result():
"""
>>> result() == (99, 17*42, 17*42)
True
"""
return (i,j,k) return (i,j,k)
__doc__ = """
>>> foo()
([0, 0], [0, 0])
"""
# Extracted from sage/plot/plot3d/index_face_set.pyx:502 # Extracted from sage/plot/plot3d/index_face_set.pyx:502
# Turns out to be a bug in implementation of PEP 3132 (Extended Iterable Unpacking) # Turns out to be a bug in implementation of PEP 3132 (Extended Iterable Unpacking)
def foo(): def foo():
"""
>>> foo()
([0, 0], [0, 0])
"""
a = b = [0,0] a = b = [0,0]
return a, b return a, b
__doc__ = u"""
>>> B().coeffs_bitsize()
[2]
"""
cdef class A: cdef class A:
def numerator(self): def numerator(self):
return self return self
...@@ -13,6 +8,10 @@ cdef int bitsize(A a): ...@@ -13,6 +8,10 @@ cdef int bitsize(A a):
coeffs = [A()] coeffs = [A()]
class B: class B:
"""
>>> B().coeffs_bitsize()
[2]
"""
def coeffs_bitsize(self): def coeffs_bitsize(self):
r = [bitsize(c.numerator())+1 for c in coeffs] r = [bitsize(c.numerator())+1 for c in coeffs]
return r return r
__doc__ = u"""
>>> spam(dict(test=2))
False
"""
def spam(dict d): def spam(dict d):
"""
>>> spam(dict(test=2))
False
"""
for elm in d: for elm in d:
return False return False
return True return True
__doc__ = u"""
>>> f(1,2,3,4,5)
()
>>> g(1,2,3,4,5)
(2,)
>>> h(1,2,3,4,5)
(2, 3)
>>> j(1,2,3,4,5)
(2, 3, 4)
>>> k(1,2,3,4,5)
(2, 3, 4)
>>> l(1,2,3,4,5)
(17, 42, 88)
>>> tuple_none()
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
>>> tuple_none_list()
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
"""
import sys import sys
if sys.version_info < (2,5): if sys.version_info < (2,5):
__doc__ = __doc__.replace( __doc__ = __doc__.replace(
...@@ -26,21 +5,37 @@ if sys.version_info < (2,5): ...@@ -26,21 +5,37 @@ if sys.version_info < (2,5):
u'iteration over non-sequence\n >>> tuple_none_list()') u'iteration over non-sequence\n >>> tuple_none_list()')
def f(obj1, obj2, obj3, obj4, obj5): def f(obj1, obj2, obj3, obj4, obj5):
"""
>>> f(1,2,3,4,5)
()
"""
obj1 = () obj1 = ()
return obj1 return obj1
def g(obj1, obj2, obj3, obj4, obj5): def g(obj1, obj2, obj3, obj4, obj5):
"""
>>> g(1,2,3,4,5)
(2,)
"""
obj1 = () obj1 = ()
obj1 = (obj2,) obj1 = (obj2,)
return obj1 return obj1
def h(obj1, obj2, obj3, obj4, obj5): def h(obj1, obj2, obj3, obj4, obj5):
"""
>>> h(1,2,3,4,5)
(2, 3)
"""
obj1 = () obj1 = ()
obj1 = (obj2,) obj1 = (obj2,)
obj1 = obj2, obj3 obj1 = obj2, obj3
return obj1 return obj1
def j(obj1, obj2, obj3, obj4, obj5): def j(obj1, obj2, obj3, obj4, obj5):
"""
>>> j(1,2,3,4,5)
(2, 3, 4)
"""
obj1 = () obj1 = ()
obj1 = (obj2,) obj1 = (obj2,)
obj1 = obj2, obj3 obj1 = obj2, obj3
...@@ -48,6 +43,10 @@ def j(obj1, obj2, obj3, obj4, obj5): ...@@ -48,6 +43,10 @@ def j(obj1, obj2, obj3, obj4, obj5):
return obj1 return obj1
def k(obj1, obj2, obj3, obj4, obj5): def k(obj1, obj2, obj3, obj4, obj5):
"""
>>> k(1,2,3,4,5)
(2, 3, 4)
"""
obj1 = () obj1 = ()
obj1 = (obj2,) obj1 = (obj2,)
obj1 = obj2, obj3 obj1 = obj2, obj3
...@@ -56,6 +55,10 @@ def k(obj1, obj2, obj3, obj4, obj5): ...@@ -56,6 +55,10 @@ def k(obj1, obj2, obj3, obj4, obj5):
return obj1 return obj1
def l(obj1, obj2, obj3, obj4, obj5): def l(obj1, obj2, obj3, obj4, obj5):
"""
>>> l(1,2,3,4,5)
(17, 42, 88)
"""
obj1 = () obj1 = ()
obj1 = (obj2,) obj1 = (obj2,)
obj1 = obj2, obj3 obj1 = obj2, obj3
...@@ -65,8 +68,18 @@ def l(obj1, obj2, obj3, obj4, obj5): ...@@ -65,8 +68,18 @@ def l(obj1, obj2, obj3, obj4, obj5):
return obj1 return obj1
def tuple_none(): def tuple_none():
"""
>>> tuple_none()
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
"""
return tuple(None) return tuple(None)
def tuple_none_list(): def tuple_none_list():
"""
>>> tuple_none_list()
Traceback (most recent call last):
TypeError: 'NoneType' object is not iterable
"""
cdef list none = None cdef list none = None
return tuple(none) return tuple(none)
__doc__ = u"""
>>> assign3(l)
(1, 2, 3)
>>> assign3(t)
(1, 2, 3)
>>> assign3_typed(t)
(1, 2, 3)
>>> assign3_int(l)
(1, 2, 3)
>>> assign3_mixed1(l)
(1, 2, 3)
>>> assign3_mixed2(l)
(1, 2, 3)
>>> assign3_mixed3(l)
(1, 2, 3)
>>> assign3_typed(l)
Traceback (most recent call last):
TypeError: Argument 't' has incorrect type (expected tuple, got list)
>>> a,b,c = (1,) # doctest: +ELLIPSIS
Traceback (most recent call last):
ValueError: ...
>>> assign3((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> assign3_typed((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> a,b,c = (1,2) # doctest: +ELLIPSIS
Traceback (most recent call last):
ValueError: ...
>>> assign3((1,2))
Traceback (most recent call last):
ValueError: need more than 2 values to unpack
>>> assign3_typed((1,2))
Traceback (most recent call last):
ValueError: need more than 2 values to unpack
>>> a,b,c = (1,2,3,4)
Traceback (most recent call last):
ValueError: too many values to unpack
>>> assign3((1,2,3,4))
Traceback (most recent call last):
ValueError: too many values to unpack
>>> assign3_typed((1,2,3,4))
Traceback (most recent call last):
ValueError: too many values to unpack
>>> a,b = 99,98
>>> a,b = t
Traceback (most recent call last):
ValueError: too many values to unpack
>>> a,b
(99, 98)
>>> test_overwrite(l)
(99, 98)
>>> test_overwrite(t)
(99, 98)
>>> test_overwrite_int(l)
(99, 98)
>>> test_overwrite_int(t)
(99, 98)
>>> test_overwrite_mixed(l)
(99, 98)
>>> test_overwrite_mixed(t)
(99, 98)
>>> test_overwrite_mixed2(l)
(99, 98)
>>> test_overwrite_mixed2(t)
(99, 98)
"""
t = (1,2,3) t = (1,2,3)
l = [1,2,3] l = [1,2,3]
def assign3(t): def assign3(t):
"""
>>> assign3(l)
(1, 2, 3)
>>> assign3(t)
(1, 2, 3)
>>> assign3((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> assign3((1,2))
Traceback (most recent call last):
ValueError: need more than 2 values to unpack
>>> assign3((1,2,3,4))
Traceback (most recent call last):
ValueError: too many values to unpack
"""
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
def assign3_typed(tuple t): def assign3_typed(tuple t):
"""
>>> assign3_typed(t)
(1, 2, 3)
>>> assign3_typed(l)
Traceback (most recent call last):
TypeError: Argument 't' has incorrect type (expected tuple, got list)
>>> a,b,c = (1,) # doctest: +ELLIPSIS
Traceback (most recent call last):
ValueError: ...
>>> assign3_typed((1,))
Traceback (most recent call last):
ValueError: need more than 1 value to unpack
>>> a,b,c = (1,2) # doctest: +ELLIPSIS
Traceback (most recent call last):
ValueError: ...
>>> assign3_typed((1,2))
Traceback (most recent call last):
ValueError: need more than 2 values to unpack
>>> a,b,c = (1,2,3,4)
Traceback (most recent call last):
ValueError: too many values to unpack
>>> assign3_typed((1,2,3,4))
Traceback (most recent call last):
ValueError: too many values to unpack
>>> a,b = 99,98
>>> a,b = t
Traceback (most recent call last):
ValueError: too many values to unpack
>>> a,b
(99, 98)
"""
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
def assign3_int(t): def assign3_int(t):
"""
>>> assign3_int(l)
(1, 2, 3)
"""
cdef int a,b,c cdef int a,b,c
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
def assign3_mixed1(t): def assign3_mixed1(t):
"""
>>> assign3_mixed1(l)
(1, 2, 3)
"""
cdef int a cdef int a
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
def assign3_mixed2(t): def assign3_mixed2(t):
"""
>>> assign3_mixed2(l)
(1, 2, 3)
"""
cdef int b cdef int b
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
def assign3_mixed3(t): def assign3_mixed3(t):
"""
>>> assign3_mixed3(l)
(1, 2, 3)
"""
cdef int c cdef int c
a,b,c = t a,b,c = t
return (a,b,c) return (a,b,c)
...@@ -113,6 +97,12 @@ def assign3_mixed4(t): ...@@ -113,6 +97,12 @@ def assign3_mixed4(t):
return (a,b,c) return (a,b,c)
def test_overwrite(t): def test_overwrite(t):
"""
>>> test_overwrite(l)
(99, 98)
>>> test_overwrite(t)
(99, 98)
"""
a,b = 99,98 a,b = 99,98
try: try:
a,b = t a,b = t
...@@ -121,6 +111,12 @@ def test_overwrite(t): ...@@ -121,6 +111,12 @@ def test_overwrite(t):
return (a,b) return (a,b)
def test_overwrite_int(t): def test_overwrite_int(t):
"""
>>> test_overwrite_int(l)
(99, 98)
>>> test_overwrite_int(t)
(99, 98)
"""
cdef int a,b cdef int a,b
a,b = 99,98 a,b = 99,98
try: try:
...@@ -130,6 +126,12 @@ def test_overwrite_int(t): ...@@ -130,6 +126,12 @@ def test_overwrite_int(t):
return (a,b) return (a,b)
def test_overwrite_mixed(t): def test_overwrite_mixed(t):
"""
>>> test_overwrite_mixed(l)
(99, 98)
>>> test_overwrite_mixed(t)
(99, 98)
"""
cdef int b cdef int b
a,b = 99,98 a,b = 99,98
try: try:
...@@ -139,6 +141,12 @@ def test_overwrite_mixed(t): ...@@ -139,6 +141,12 @@ def test_overwrite_mixed(t):
return (a,b) return (a,b)
def test_overwrite_mixed2(t): def test_overwrite_mixed2(t):
"""
>>> test_overwrite_mixed2(l)
(99, 98)
>>> test_overwrite_mixed2(t)
(99, 98)
"""
cdef int a cdef int a
a,b = 99,98 a,b = 99,98
try: try:
......
__doc__ = u""" def test1(t):
"""
>>> test1( (1,2,3) ) >>> test1( (1,2,3) )
1 1
>>> test3( (1,2,3) ) """
3
>>> test( (1,2,3) )
3
>>> testnonsense() # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
"""
def test1(t):
t,a,b = t t,a,b = t
return t return t
def test3(t): def test3(t):
"""
>>> test3( (1,2,3) )
3
"""
a,b,t = t a,b,t = t
return t return t
def test(t): def test(t):
"""
>>> test( (1,2,3) )
3
"""
t,t,t = t t,t,t = t
return t return t
def testnonsense(): def testnonsense():
"""
>>> testnonsense() # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: ...
"""
t,t,t = 1*2 t,t,t = 1*2
return t return t
# cython: infer_types = True # cython: infer_types = True
__doc__ = u"""
>>> simple()
>>> multiple_assignments()
>>> arithmatic()
>>> cascade()
>>> increment()
>>> loop()
"""
from cython cimport typeof from cython cimport typeof
def simple(): def simple():
"""
>>> simple()
"""
i = 3 i = 3
assert typeof(i) == "long", typeof(i) assert typeof(i) == "long", typeof(i)
x = 1.41 x = 1.41
...@@ -32,6 +27,9 @@ def simple(): ...@@ -32,6 +27,9 @@ def simple():
assert typeof(t) == "tuple object", typeof(t) assert typeof(t) == "tuple object", typeof(t)
def multiple_assignments(): def multiple_assignments():
"""
>>> multiple_assignments()
"""
a = 3 a = 3
a = 4 a = 4
a = 5 a = 5
...@@ -46,6 +44,9 @@ def multiple_assignments(): ...@@ -46,6 +44,9 @@ def multiple_assignments():
assert typeof(c) == "Python object" assert typeof(c) == "Python object"
def arithmatic(): def arithmatic():
"""
>>> arithmatic()
"""
a = 1 + 2 a = 1 + 2
assert typeof(a) == "long" assert typeof(a) == "long"
b = 1 + 1.5 b = 1 + 1.5
...@@ -56,6 +57,9 @@ def arithmatic(): ...@@ -56,6 +57,9 @@ def arithmatic():
assert typeof(d) == "Python object" assert typeof(d) == "Python object"
def cascade(): def cascade():
"""
>>> cascade()
"""
a = 1.0 a = 1.0
b = a + 2 b = a + 2
c = b + 3 c = b + 3
...@@ -74,11 +78,17 @@ def cascaded_assignment(): ...@@ -74,11 +78,17 @@ def cascaded_assignment():
assert typeof(e) == "double" assert typeof(e) == "double"
def increment(): def increment():
"""
>>> increment()
"""
a = 5 a = 5
a += 1 a += 1
assert typeof(a) == "long" assert typeof(a) == "long"
def loop(): def loop():
"""
>>> loop()
"""
for a in range(10): for a in range(10):
pass pass
assert typeof(a) == "long" assert typeof(a) == "long"
......
...@@ -10,34 +10,37 @@ __doc__ = u""" ...@@ -10,34 +10,37 @@ __doc__ = u"""
>>> print( "%d" % IntLongC() ) >>> print( "%d" % IntLongC() )
3 3
>>> getint( Int() )
2
>>> getint( Long() )
3
>>> getint( IntLongA() )
2
>>> getint( IntLongB() )
2
>>> getint( IntLongC() )
3
>>> getlong( Int() )
2
>>> getlong( Long() )
3
>>> getlong( IntLongA() )
2
>>> getlong( IntLongB() )
2
>>> getlong( IntLongC() )
3
""" """
def getint(int i): def getint(int i):
"""
>>> getint( Int() )
2
>>> getint( Long() )
3
>>> getint( IntLongA() )
2
>>> getint( IntLongB() )
2
>>> getint( IntLongC() )
3
"""
return i return i
def getlong(long long i): def getlong(long long i):
"""
>>> getlong( Int() )
2
>>> getlong( Long() )
3
>>> getlong( IntLongA() )
2
>>> getlong( IntLongB() )
2
>>> getlong( IntLongC() )
3
"""
return <int>i return <int>i
......
__doc__ = u"""
>>> l = [1,2,3,4]
>>> slice_list(l)
[2, 3]
>>> slice_tuple(tuple(l))
(2, 3)
>>> l2 = l[:]
>>> slice_list_assign_list(l2)
[1, 1, 2, 3, 4, 4]
>>> l2 = l[:]
>>> slice_list_assign_tuple(l2)
[1, 1, 2, 3, 4, 4]
>>> l2 = l[:]
>>> slice_list_assign(l2, (1,2,3,4))
[1, 1, 2, 3, 4, 4]
>>> l2 = l[:]
>>> slice_list_assign(l2, dict(zip(l,l)))
[1, 1, 2, 3, 4, 4]
>>> print("%s" % slice_charp('abcdefg'))
bc
>>> print("%s" % slice_charp_repeat('abcdefg'))
cd
"""
def slice_list(list l): def slice_list(list l):
"""
>>> slice_list([1,2,3,4])
[2, 3]
"""
return l[1:3] return l[1:3]
def slice_list_copy(list l): def slice_list_copy(list l):
...@@ -36,27 +10,63 @@ def slice_list_copy(list l): ...@@ -36,27 +10,63 @@ def slice_list_copy(list l):
return retlist return retlist
def slice_tuple(tuple t): def slice_tuple(tuple t):
"""
>>> l = [1,2,3,4]
>>> slice_tuple(tuple(l))
(2, 3)
"""
return t[1:3] return t[1:3]
def slice_list_assign_list(list l): def slice_list_assign_list(list l):
"""
>>> l = [1,2,3,4]
>>> l2 = l[:]
>>> slice_list_assign_list(l2)
[1, 1, 2, 3, 4, 4]
"""
l[1:3] = [1,2,3,4] l[1:3] = [1,2,3,4]
return l return l
def slice_list_assign_tuple(list l): def slice_list_assign_tuple(list l):
"""
>>> l = [1,2,3,4]
>>> l2 = l[:]
>>> slice_list_assign_tuple(l2)
[1, 1, 2, 3, 4, 4]
"""
l[1:3] = (1,2,3,4) l[1:3] = (1,2,3,4)
return l return l
def slice_list_assign(list l, value): def slice_list_assign(list l, value):
"""
>>> l = [1,2,3,4]
>>> l2 = l[:]
>>> slice_list_assign(l2, (1,2,3,4))
[1, 1, 2, 3, 4, 4]
>>> l2 = l[:]
>>> slice_list_assign(l2, dict(zip(l,l)))
[1, 1, 2, 3, 4, 4]
"""
l[1:3] = value l[1:3] = value
return l return l
def slice_charp(py_string_arg): def slice_charp(py_string_arg):
"""
>>> l = [1,2,3,4]
>>> print("%s" % slice_charp('abcdefg'))
bc
"""
cdef bytes py_string = py_string_arg.encode(u'ASCII') cdef bytes py_string = py_string_arg.encode(u'ASCII')
cdef char* s = py_string cdef char* s = py_string
return s[1:3].decode(u'ASCII') return s[1:3].decode(u'ASCII')
def slice_charp_repeat(py_string_arg): def slice_charp_repeat(py_string_arg):
"""
>>> l = [1,2,3,4]
>>> print("%s" % slice_charp_repeat('abcdefg'))
cd
"""
cdef bytes py_string = py_string_arg.encode(u'ASCII') cdef bytes py_string = py_string_arg.encode(u'ASCII')
cdef char* s = py_string cdef char* s = py_string
cdef bytes slice_val = s[1:6] cdef bytes slice_val = s[1:6]
......
__doc__ = u"""
>>> f()
42.0
42.0
>>> global_vars(12.0)
12.0 12.0
>>> readonly()
Traceback (most recent call last):
...
TypeError: readonly attribute
>>> longdouble_access()
Traceback (most recent call last):
...
SystemError: bad memberdescr type
"""
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u'TypeError:', u'AttributeError:') __doc__ = __doc__.replace(u'TypeError:', u'AttributeError:')
...@@ -38,22 +22,42 @@ cdef class MyClass: ...@@ -38,22 +22,42 @@ cdef class MyClass:
self.float_isreally_longdouble = 42.0 self.float_isreally_longdouble = 42.0
def global_vars(x): def global_vars(x):
"""
>>> global_vars(12.0)
12.0 12.0
"""
global global_tdef, global_double global global_tdef, global_double
global_tdef = x global_tdef = x
global_double = x global_double = x
print global_tdef, global_double print global_tdef, global_double
def f(): def f():
"""
>>> f()
42.0
42.0
"""
c = MyClass() c = MyClass()
print c.actual_double print c.actual_double
print c.float_isreally_double print c.float_isreally_double
def longdouble_access(): def longdouble_access():
"""
>>> longdouble_access()
Traceback (most recent call last):
...
SystemError: bad memberdescr type
"""
c = MyClass() c = MyClass()
print c.float_isreally_longdouble print c.float_isreally_longdouble
def readonly(): def readonly():
"""
>>> readonly()
Traceback (most recent call last):
...
TypeError: readonly attribute
"""
c = MyClass() c = MyClass()
c.actual_double = 3 c.actual_double = 3
__doc__ = u"""
>>> simple()
int
long
long long
int *
int **
A
B
X
Python object
>>> expression()
double
double complex
int
unsigned int
"""
from cython cimport typeof from cython cimport typeof
cdef class A: cdef class A:
...@@ -30,6 +11,18 @@ cdef struct X: ...@@ -30,6 +11,18 @@ cdef struct X:
double complex b double complex b
def simple(): def simple():
"""
>>> simple()
int
long
long long
int *
int **
A
B
X
Python object
"""
cdef int i = 0 cdef int i = 0
cdef long l = 0 cdef long l = 0
cdef long long ll = 0 cdef long long ll = 0
...@@ -50,6 +43,13 @@ def simple(): ...@@ -50,6 +43,13 @@ def simple():
used = i, l, ll, <long>iptr, <long>iptrptr, a, b, x used = i, l, ll, <long>iptr, <long>iptrptr, a, b, x
def expression(): def expression():
"""
>>> expression()
double
double complex
int
unsigned int
"""
cdef X x = X(a=1, b=2) cdef X x = X(a=1, b=2)
cdef X *xptr = &x cdef X *xptr = &x
cdef short s = 0 cdef short s = 0
......
__doc__ = u""" def f(obj1, obj2, obj3):
"""
>>> f(1, 2, 3) >>> f(1, 2, 3)
(-3, -4, 1) (-3, -4, 1)
""" """
def f(obj1, obj2, obj3):
cdef int bool1, bool2 cdef int bool1, bool2
cdef int int1, int2 cdef int int1, int2
cdef char *str1 cdef char *str1
......
__doc__ = u""" def f(obj1, obj2, obj3, obj4, obj5):
"""
>>> f(1, (2,), (3,4,5), (6,(7,(8,9))), 0) >>> f(1, (2,), (3,4,5), (6,(7,(8,9))), 0)
(8, 9, (8, 9), (6, (7, (8, 9))), 0) (8, 9, (8, 9), (6, (7, (8, 9))), 0)
""" """
def f(obj1, obj2, obj3, obj4, obj5):
obj1, = obj2 obj1, = obj2
obj1, obj2 = obj2 + obj2 obj1, obj2 = obj2 + obj2
obj1, obj2, obj3 = obj3 obj1, obj2, obj3 = obj3
......
__doc__ = u""" def unpack_normal(l):
"""
>>> unpack_normal([1,2]) >>> unpack_normal([1,2])
(1, 2) (1, 2)
>>> unpack_normal([1,2,3]) # doctest: +ELLIPSIS >>> unpack_normal([1,2,3]) # doctest: +ELLIPSIS
Traceback (most recent call last): Traceback (most recent call last):
ValueError: ... ValueError: ...
"""
a,b = l
return a,b
def unpack_comp(l):
"""
>>> unpack_comp([1,2]) >>> unpack_comp([1,2])
(1, 2) (1, 2)
>>> unpack_comp([1,2,3]) # doctest: +ELLIPSIS >>> unpack_comp([1,2,3]) # doctest: +ELLIPSIS
Traceback (most recent call last): Traceback (most recent call last):
ValueError: ... ValueError: ...
"""
a,b = [ n for n in l ]
return a,b
def unpack_expr(l):
"""
>>> unpack_expr([1,2]) >>> unpack_expr([1,2])
(1, 4) (1, 4)
>>> unpack_expr([1,2,3]) # doctest: +ELLIPSIS >>> unpack_expr([1,2,3]) # doctest: +ELLIPSIS
Traceback (most recent call last): Traceback (most recent call last):
ValueError: ... ValueError: ...
""" """
def unpack_normal(l):
a,b = l
return a,b
def unpack_comp(l):
a,b = [ n for n in l ]
return a,b
def unpack_expr(l):
a,b = [ n*n for n in l ] a,b = [ n*n for n in l ]
return a,b return a,b
__doc__ = u"""
>>> swallow()
"""
cdef grail(char *blarg, ...): cdef grail(char *blarg, ...):
pass pass
def swallow(): def swallow():
"""
>>> swallow()
"""
grail("spam") grail("spam")
grail("spam", 42) grail("spam", 42)
__doc__ = u"""
>>> test()
"""
cdef grail(char *blarg, ...): cdef grail(char *blarg, ...):
pass pass
def test(): def test():
"""
>>> test()
"""
grail(b"test") grail(b"test")
grail(b"test", b"toast") grail(b"test", b"toast")
__doc__ = u"""
>>> test() == 55 + 66
True
"""
def test(): def test():
"""
>>> test() == 55 + 66
True
"""
cdef int a,b cdef int a,b
foo=(55,66) foo=(55,66)
a,b=foo a,b=foo
......
__doc__ = u""" def f(x):
"""
>>> f(1) >>> f(1)
(1, 17) (1, 17)
>>> g() """
1
"""
def f(x):
cdef int y cdef int y
z = 42 z = 42
with nogil: with nogil:
...@@ -14,6 +11,10 @@ def f(x): ...@@ -14,6 +11,10 @@ def f(x):
return z,y return z,y
def g(): def g():
"""
>>> g()
1
"""
with nogil: with nogil:
h() h()
return 1 return 1
......
from __future__ import with_statement from __future__ import with_statement
__doc__ = u"""
>>> no_as()
enter
hello
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> basic()
enter
value
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> with_return()
enter
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> with_pass()
enter
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> with_exception(None)
enter
value
exit <type 'type'> <type 'MyException'> <type 'traceback'>
outer except
>>> with_exception(True)
enter
value
exit <type 'type'> <type 'MyException'> <type 'traceback'>
>>> multitarget()
enter
1 2 3 4 5
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> tupletarget()
enter
(1, 2, (3, (4, 5)))
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
>>> typed()
enter
10
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
import sys import sys
if sys.version_info < (2,5): if sys.version_info < (2,5):
...@@ -63,24 +26,57 @@ class ContextManager(object): ...@@ -63,24 +26,57 @@ class ContextManager(object):
return self.value return self.value
def no_as(): def no_as():
"""
>>> no_as()
enter
hello
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager(u"value"): with ContextManager(u"value"):
print u"hello" print u"hello"
def basic(): def basic():
"""
>>> basic()
enter
value
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager(u"value") as x: with ContextManager(u"value") as x:
print x print x
def with_pass(): def with_pass():
"""
>>> with_pass()
enter
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager(u"value") as x: with ContextManager(u"value") as x:
pass pass
def with_return(): def with_return():
"""
>>> with_return()
enter
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager(u"value") as x: with ContextManager(u"value") as x:
# FIXME: DISABLED - currently crashes!! # FIXME: DISABLED - currently crashes!!
# return x # return x
pass pass
def with_exception(exit_ret): def with_exception(exit_ret):
"""
>>> with_exception(None)
enter
value
exit <type 'type'> <type 'MyException'> <type 'traceback'>
outer except
>>> with_exception(True)
enter
value
exit <type 'type'> <type 'MyException'> <type 'traceback'>
"""
try: try:
with ContextManager(u"value", exit_ret=exit_ret) as value: with ContextManager(u"value", exit_ret=exit_ret) as value:
print value print value
...@@ -89,14 +85,32 @@ def with_exception(exit_ret): ...@@ -89,14 +85,32 @@ def with_exception(exit_ret):
print u"outer except" print u"outer except"
def multitarget(): def multitarget():
"""
>>> multitarget()
enter
1 2 3 4 5
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager((1, 2, (3, (4, 5)))) as (a, b, (c, (d, e))): with ContextManager((1, 2, (3, (4, 5)))) as (a, b, (c, (d, e))):
print a, b, c, d, e print a, b, c, d, e
def tupletarget(): def tupletarget():
"""
>>> tupletarget()
enter
(1, 2, (3, (4, 5)))
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
with ContextManager((1, 2, (3, (4, 5)))) as t: with ContextManager((1, 2, (3, (4, 5)))) as t:
print t print t
def typed(): def typed():
"""
>>> typed()
enter
10
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
"""
cdef unsigned char i cdef unsigned char i
c = ContextManager(255) c = ContextManager(255)
with c as i: with c as i:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment