Commit c8b85056 authored by Dag Sverre Seljebotn's avatar Dag Sverre Seljebotn

merge

parents ea85d044 09f35807
...@@ -27,8 +27,6 @@ Options: ...@@ -27,8 +27,6 @@ Options:
-z, --pre-import <module> If specified, assume undeclared names in this -z, --pre-import <module> If specified, assume undeclared names in this
module. Emulates the behavior of putting module. Emulates the behavior of putting
"from <module> import *" at the top of the file. "from <module> import *" at the top of the file.
--incref-local-binop Force local an extra incref on local variables before
performing any binary operations.
--cleanup <level> Release interned objects on python exit, for memory debugging. --cleanup <level> Release interned objects on python exit, for memory debugging.
Level indicates aggressiveness, default 0 releases nothing. Level indicates aggressiveness, default 0 releases nothing.
-w, --working <directory> Sets the working directory for Cython (the directory modules -w, --working <directory> Sets the working directory for Cython (the directory modules
...@@ -108,8 +106,6 @@ def parse_command_line(args): ...@@ -108,8 +106,6 @@ def parse_command_line(args):
Options.embed_pos_in_docstring = 1 Options.embed_pos_in_docstring = 1
elif option in ("-z", "--pre-import"): elif option in ("-z", "--pre-import"):
Options.pre_import = pop_arg() Options.pre_import = pop_arg()
elif option == "--incref-local-binop":
Options.incref_local_binop = 1
elif option == "--cleanup": elif option == "--cleanup":
Options.generate_cleanup_code = int(pop_arg()) Options.generate_cleanup_code = int(pop_arg())
elif option in ("-D", "--no-docstrings"): elif option in ("-D", "--no-docstrings"):
......
...@@ -4488,8 +4488,6 @@ class BinopNode(ExprNode): ...@@ -4488,8 +4488,6 @@ class BinopNode(ExprNode):
self.coerce_operands_to_pyobjects(env) self.coerce_operands_to_pyobjects(env)
self.type = py_object_type self.type = py_object_type
self.is_temp = 1 self.is_temp = 1
if Options.incref_local_binop and self.operand1.type.is_pyobject:
self.operand1 = self.operand1.coerce_to_temp(env)
else: else:
self.analyse_c_operation(env) self.analyse_c_operation(env)
...@@ -5538,6 +5536,7 @@ class CoercionNode(ExprNode): ...@@ -5538,6 +5536,7 @@ class CoercionNode(ExprNode):
# arg ExprNode node being coerced # arg ExprNode node being coerced
subexprs = ['arg'] subexprs = ['arg']
constant_result = not_a_constant
def __init__(self, arg): def __init__(self, arg):
self.pos = arg.pos self.pos = arg.pos
......
...@@ -2579,7 +2579,7 @@ __Pyx_char2wchar(char* arg) ...@@ -2579,7 +2579,7 @@ __Pyx_char2wchar(char* arg)
mbstate_t mbs; mbstate_t mbs;
#endif #endif
if (argsize != (size_t)-1) { if (argsize != (size_t)-1) {
res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); res = (wchar_t *)malloc((argsize+1)*sizeof(wchar_t));
if (!res) if (!res)
goto oom; goto oom;
count = mbstowcs(res, arg, argsize+1); count = mbstowcs(res, arg, argsize+1);
...@@ -2593,7 +2593,7 @@ __Pyx_char2wchar(char* arg) ...@@ -2593,7 +2593,7 @@ __Pyx_char2wchar(char* arg)
if (*tmp == 0) if (*tmp == 0)
return res; return res;
} }
PyMem_Free(res); free(res);
} }
/* Conversion failed. Fall back to escaping with surrogateescape. */ /* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC #ifdef HAVE_MBRTOWC
...@@ -2602,7 +2602,7 @@ __Pyx_char2wchar(char* arg) ...@@ -2602,7 +2602,7 @@ __Pyx_char2wchar(char* arg)
/* Overallocate; as multi-byte characters are in the argument, the /* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */ actual output could use less memory. */
argsize = strlen(arg) + 1; argsize = strlen(arg) + 1;
res = PyMem_Malloc(argsize*sizeof(wchar_t)); res = malloc(argsize*sizeof(wchar_t));
if (!res) goto oom; if (!res) goto oom;
in = (unsigned char*)arg; in = (unsigned char*)arg;
out = res; out = res;
...@@ -2645,7 +2645,7 @@ __Pyx_char2wchar(char* arg) ...@@ -2645,7 +2645,7 @@ __Pyx_char2wchar(char* arg)
/* Cannot use C locale for escaping; manually escape as if charset /* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */ correctly in the locale's charset, which must be an ASCII superset. */
res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); res = malloc((strlen(arg)+1)*sizeof(wchar_t));
if (!res) goto oom; if (!res) goto oom;
in = (unsigned char*)arg; in = (unsigned char*)arg;
out = res; out = res;
...@@ -2665,9 +2665,9 @@ oom: ...@@ -2665,9 +2665,9 @@ oom:
int int
main(int argc, char **argv) main(int argc, char **argv)
{ {
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); wchar_t **argv_copy = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */ /* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); wchar_t **argv_copy2 = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
int i, res; int i, res;
char *oldloc; char *oldloc;
if (!argv_copy || !argv_copy2) { if (!argv_copy || !argv_copy2) {
...@@ -2685,10 +2685,10 @@ main(int argc, char **argv) ...@@ -2685,10 +2685,10 @@ main(int argc, char **argv)
free(oldloc); free(oldloc);
res = __Pyx_main(argc, argv_copy); res = __Pyx_main(argc, argv_copy);
for (i = 0; i < argc; i++) { for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]); free(argv_copy2[i]);
} }
PyMem_Free(argv_copy); free(argv_copy);
PyMem_Free(argv_copy2); free(argv_copy2);
return res; return res;
} }
#endif #endif
......
...@@ -3092,8 +3092,6 @@ class InPlaceAssignmentNode(AssignmentNode): ...@@ -3092,8 +3092,6 @@ class InPlaceAssignmentNode(AssignmentNode):
self.dup = self.create_dup_node(env) # re-assigns lhs to a shallow copy self.dup = self.create_dup_node(env) # re-assigns lhs to a shallow copy
self.rhs.analyse_types(env) self.rhs.analyse_types(env)
self.lhs.analyse_target_types(env) self.lhs.analyse_target_types(env)
if Options.incref_local_binop and self.dup.type.is_pyobject:
self.dup = self.dup.coerce_to_temp(env)
import ExprNodes import ExprNodes
if self.lhs.type.is_pyobject: if self.lhs.type.is_pyobject:
self.rhs = self.rhs.coerce_to_pyobject(env) self.rhs = self.rhs.coerce_to_pyobject(env)
......
This diff is collapsed.
...@@ -10,12 +10,6 @@ gcc_branch_hints = 1 ...@@ -10,12 +10,6 @@ gcc_branch_hints = 1
pre_import = None pre_import = None
docstrings = True docstrings = True
# This is a SAGE-specific option that will
# cause Cython to incref local variables before
# performing a binary operation on them, for
# safe detection of inplace operators.
incref_local_binop = 0
# Decref global variables in this module on exit for garbage collection. # Decref global variables in this module on exit for garbage collection.
# 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects # 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects
# Mostly for reducing noise for Valgrind, only executes at process exit # Mostly for reducing noise for Valgrind, only executes at process exit
......
...@@ -621,8 +621,8 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *); ...@@ -621,8 +621,8 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
""", """,
impl=""" impl="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
const %(type)s neg_one = (%(type)s)-1, zero = 0; const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
const int is_unsigned = neg_one > zero; const int is_unsigned = neg_one > const_zero;
if (sizeof(%(type)s) < sizeof(long)) { if (sizeof(%(type)s) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x); long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(%(type)s)val)) { if (unlikely(val != (long)(%(type)s)val)) {
...@@ -646,8 +646,8 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *); ...@@ -646,8 +646,8 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
""", """,
impl=""" impl="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
const %(type)s neg_one = (%(type)s)-1, zero = 0; const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
const int is_unsigned = neg_one > zero; const int is_unsigned = neg_one > const_zero;
#if PY_VERSION_HEX < 0x03000000 #if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_Check(x))) { if (likely(PyInt_Check(x))) {
long val = PyInt_AS_LONG(x); long val = PyInt_AS_LONG(x);
...@@ -687,8 +687,8 @@ static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *); ...@@ -687,8 +687,8 @@ static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
""", """,
impl=""" impl="""
static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) { static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
const %(type)s neg_one = (%(type)s)-1, zero = 0; const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
const int is_unsigned = neg_one > zero; const int is_unsigned = neg_one > const_zero;
if (sizeof(%(type)s) == sizeof(char)) { if (sizeof(%(type)s) == sizeof(char)) {
if (is_unsigned) if (is_unsigned)
return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x); return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
...@@ -734,8 +734,8 @@ static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s); ...@@ -734,8 +734,8 @@ static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
""", """,
impl=""" impl="""
static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) { static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
const %(type)s neg_one = (%(type)s)-1, zero = 0; const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
const int is_unsigned = neg_one > zero; const int is_unsigned = neg_one > const_zero;
if (sizeof(%(type)s) < sizeof(long)) { if (sizeof(%(type)s) < sizeof(long)) {
return PyInt_FromLong((long)val); return PyInt_FromLong((long)val);
} else if (sizeof(%(type)s) == sizeof(long)) { } else if (sizeof(%(type)s) == sizeof(long)) {
...@@ -882,6 +882,12 @@ class CComplexType(CNumericType): ...@@ -882,6 +882,12 @@ class CComplexType(CNumericType):
return self.real_type == other.real_type return self.real_type == other.real_type
else: else:
return False return False
def __ne__(self, other):
if isinstance(self, CComplexType) and isinstance(other, CComplexType):
return self.real_type != other.real_type
else:
return True
def __lt__(self, other): def __lt__(self, other):
if isinstance(self, CComplexType) and isinstance(other, CComplexType): if isinstance(self, CComplexType) and isinstance(other, CComplexType):
......
# Makefile for creating our standalone Cython program # Makefile for creating our standalone Cython program
PYVERSION=2.3 PYVERSION=$(shell python -c "import sys; print sys.version[:3]")
PYPREFIX=/usr PYPREFIX=$(shell python -c "import sys; print sys.prefix")
INCLUDES=-I$(PYPREFIX)/include/python$(PYVERSION) INCLUDES=-I$(PYPREFIX)/include/python$(PYVERSION)
embedded: embedded.o embedded: embedded.o
gcc -o $@ $^ -lpython$(PYVERSION) gcc -o $@ $^ -lpython$(PYVERSION)
embedded.o: embedded.c embedded.o: embedded.c
gcc -c $^ $(INCLUDES) gcc -c $^ $(INCLUDES)
embedded.c: embedded.pyx embedded.c: embedded.pyx
@python ../../cython.py --embed embedded.pyx @python ../../cython.py --embed embedded.pyx
all: embedded all: embedded
clean: clean:
@echo Cleaning Demos/embed @echo Cleaning Demos/embed
@rm -f *~ *.o *.so core core.* *.c embedded @rm -f *~ *.o *.so core core.* *.c embedded test.output
test: clean all
./embedded > test.output
python assert_equal.py embedded.output test.output
import sys
if open(sys.argv[1]).read() != open(sys.argv[2]).read():
print "Files differ"
sys.exit(1)
else:
print "Files identical"
__main__
Hi, I'm embedded.
...@@ -148,7 +148,7 @@ char2wchar(char* arg) ...@@ -148,7 +148,7 @@ char2wchar(char* arg)
mbstate_t mbs; mbstate_t mbs;
#endif #endif
if (argsize != (size_t)-1) { if (argsize != (size_t)-1) {
res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); res = (wchar_t *)malloc((argsize+1)*sizeof(wchar_t));
if (!res) if (!res)
goto oom; goto oom;
count = mbstowcs(res, arg, argsize+1); count = mbstowcs(res, arg, argsize+1);
...@@ -162,7 +162,7 @@ char2wchar(char* arg) ...@@ -162,7 +162,7 @@ char2wchar(char* arg)
if (*tmp == 0) if (*tmp == 0)
return res; return res;
} }
PyMem_Free(res); free(res);
} }
/* Conversion failed. Fall back to escaping with surrogateescape. */ /* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC #ifdef HAVE_MBRTOWC
...@@ -171,7 +171,7 @@ char2wchar(char* arg) ...@@ -171,7 +171,7 @@ char2wchar(char* arg)
/* Overallocate; as multi-byte characters are in the argument, the /* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */ actual output could use less memory. */
argsize = strlen(arg) + 1; argsize = strlen(arg) + 1;
res = PyMem_Malloc(argsize*sizeof(wchar_t)); res = malloc(argsize*sizeof(wchar_t));
if (!res) goto oom; if (!res) goto oom;
in = (unsigned char*)arg; in = (unsigned char*)arg;
out = res; out = res;
...@@ -214,7 +214,7 @@ char2wchar(char* arg) ...@@ -214,7 +214,7 @@ char2wchar(char* arg)
/* Cannot use C locale for escaping; manually escape as if charset /* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */ correctly in the locale's charset, which must be an ASCII superset. */
res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); res = malloc((strlen(arg)+1)*sizeof(wchar_t));
if (!res) goto oom; if (!res) goto oom;
in = (unsigned char*)arg; in = (unsigned char*)arg;
out = res; out = res;
...@@ -234,9 +234,9 @@ oom: ...@@ -234,9 +234,9 @@ oom:
int int
main(int argc, char **argv) main(int argc, char **argv)
{ {
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); wchar_t **argv_copy = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */ /* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); wchar_t **argv_copy2 = (wchar_t **)malloc(sizeof(wchar_t*)*argc);
int i, res; int i, res;
char *oldloc; char *oldloc;
if (!argv_copy || !argv_copy2) { if (!argv_copy || !argv_copy2) {
...@@ -254,10 +254,10 @@ main(int argc, char **argv) ...@@ -254,10 +254,10 @@ main(int argc, char **argv)
free(oldloc); free(oldloc);
res = python_main(argc, argv_copy); res = python_main(argc, argv_copy);
for (i = 0; i < argc; i++) { for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]); free(argv_copy2[i]);
} }
PyMem_Free(argv_copy); free(argv_copy);
PyMem_Free(argv_copy2); free(argv_copy2);
return res; return res;
} }
#endif""" #endif"""
...@@ -127,6 +127,10 @@ class TestBuilder(object): ...@@ -127,6 +127,10 @@ class TestBuilder(object):
continue continue
suite.addTest( suite.addTest(
self.handle_directory(path, filename)) self.handle_directory(path, filename))
if sys.platform not in ['win32'] and sys.version_info[0] < 3:
# Non-Windows makefile, can't run Cython under Py3.
if [1 for selector in self.selectors if selector("embedded")]:
suite.addTest(unittest.makeSuite(EmbedTest))
return suite return suite
def handle_directory(self, path, context): def handle_directory(self, path, context):
...@@ -429,6 +433,7 @@ is_private_field = re.compile('^_[^_]').match ...@@ -429,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+
...@@ -555,6 +560,28 @@ def collect_doctests(path, module_prefix, suite, selectors): ...@@ -555,6 +560,28 @@ def collect_doctests(path, module_prefix, suite, selectors):
except ValueError: # no tests except ValueError: # no tests
pass pass
# TODO: Support cython_freeze needed here as well.
# TODO: Windows support.
class EmbedTest(unittest.TestCase):
working_dir = "Demos/embed"
def setUp(self):
self.old_dir = os.getcwd()
os.chdir(self.working_dir)
os.system("make clean > /dev/null")
def tearDown(self):
try:
os.system("make clean > /dev/null")
except:
pass
os.chdir(self.old_dir)
def test_embed(self):
self.assert_(os.system("make test > make.output") == 0)
class MissingDependencyExcluder: class MissingDependencyExcluder:
def __init__(self, deps): def __init__(self, deps):
# deps: { module name : matcher func } # deps: { module name : matcher func }
......
...@@ -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})
...@@ -75,6 +75,42 @@ def slice_charptr_for_loop_c(): ...@@ -75,6 +75,42 @@ def slice_charptr_for_loop_c():
print [ chr(c) for c in cstring[1:5] ] print [ chr(c) for c in cstring[1:5] ]
print [ chr(c) for c in cstring[4:9] ] print [ chr(c) for c in cstring[4:9] ]
## @cython.test_assert_path_exists("//ForFromStatNode",
## "//ForFromStatNode//IndexNode")
## @cython.test_fail_if_path_exists("//ForInStatNode")
## def slice_charptr_for_loop_c_step():
## """
## >>> slice_charptr_for_loop_c()
## ['c', 'b', 'a']
## ['b', 'c', 'A', 'B']
## ['p', 't', 'q', 'C', 'B']
## """
## cdef char c
## print [ chr(c) for c in cstring[:3:-1] ]
## print [ chr(c) for c in cstring[1:5:2] ]
## print [ chr(c) for c in cstring[4:9:-1] ]
@cython.test_assert_path_exists("//ForFromStatNode",
"//ForFromStatNode//IndexNode")
@cython.test_fail_if_path_exists("//ForInStatNode")
def slice_charptr_for_loop_c_dynamic_bounds():
"""
>>> slice_charptr_for_loop_c()
['a', 'b', 'c']
['b', 'c', 'A', 'B']
['B', 'C', 'q', 't', 'p']
"""
cdef char c
print [ chr(c) for c in cstring[0:return3()] ]
print [ chr(c) for c in cstring[return1():return5()] ]
print [ chr(c) for c in cstring[return4():return9()] ]
cdef return1(): return 1
cdef return3(): return 3
cdef return4(): return 4
cdef return5(): return 5
cdef return9(): return 9
@cython.test_assert_path_exists("//ForFromStatNode", @cython.test_assert_path_exists("//ForFromStatNode",
"//ForFromStatNode//SliceIndexNode") "//ForFromStatNode//SliceIndexNode")
@cython.test_fail_if_path_exists("//ForInStatNode") @cython.test_fail_if_path_exists("//ForInStatNode")
......
__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)
......
...@@ -31,51 +31,17 @@ True ...@@ -31,51 +31,17 @@ True
True True
>>> all([div_int_py(a,b) == a // b for a in range(-10, 10) for b in range(-10, 10) if b != 0]) >>> all([div_int_py(a,b) == a // b for a in range(-10, 10) for b in range(-10, 10) if b != 0])
True True
>>> def simple_warn(msg, *args): print(msg)
>>> import warnings
>>> 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
""" """
import warnings
orig_showwarning = warnings.showwarning
true_py_functions = {}
exec "def simple_warn(msg, *args): print(msg)" in true_py_functions
simple_warn = true_py_functions['simple_warn']
del true_py_functions
def _all(seq): def _all(seq):
for x in seq: for x in seq:
if not x: if not x:
...@@ -137,16 +103,40 @@ def test_cdiv_cmod(short a, short b): ...@@ -137,16 +103,40 @@ 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):
"""
>>> warnings.showwarning = simple_warn
>>> mod_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-7
>>> warnings.showwarning = orig_showwarning
"""
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):
"""
>>> warnings.showwarning = simple_warn
>>> div_int_c_warn(-17, 10)
division with oppositely signed operands, C and Python semantics differ
-1
>>> warnings.showwarning = orig_showwarning
"""
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):
"""
>>> warnings.showwarning = simple_warn
>>> 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
>>> warnings.showwarning = orig_showwarning
"""
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 +148,16 @@ cdef int verbose_call(int x): ...@@ -158,6 +148,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 +165,14 @@ def mod_div_zero_int(int a, int b, int c): ...@@ -165,6 +165,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 +180,14 @@ def mod_div_zero_float(float a, float b, float c): ...@@ -172,4 +180,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""" 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))
"""
return +z, -z, z+w, z-w, z*w, z/w
## XXX this is not working @cython.cdivision(False)
## >>> test_div_by_zero(4j) def test_div_by_zero(double complex z):
## -0.25j """
## >>> test_div_by_zero(0) >>> test_div_by_zero(4j)
## Traceback (most recent call last): -0.25j
## ... >>> test_div_by_zero(0)
## ZeroDivisionError: float division Traceback (most recent call last):
...
ZeroDivisionError: float division
"""
return 1/z
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 +44,17 @@ __doc__ = u""" ...@@ -26,7 +44,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 +63,62 @@ __doc__ = u""" ...@@ -35,93 +63,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 +127,15 @@ def test_conjugate_typedef(cdouble z): ...@@ -130,7 +127,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
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @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
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @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):
@cython.test_fail_if_path_exists("//SimpleCallNode//NameNode[@name = 'enumerate']") @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,49 @@ def empty_c_enumerate(): ...@@ -123,16 +110,49 @@ 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
@cython.test_fail_if_path_exists("//SimpleCallNode") @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
@cython.test_fail_if_path_exists("//SimpleCallNode")
def convert_target_enumerate(L):
"""
>>> convert_target_enumerate([2,3,5])
0 2
1 3
2 5
"""
cdef int a,b
for a, b in enumerate(L):
print a,b
__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()
......
This diff is collapsed.
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
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u" u'", u" '").replace(u' u"', u' "')
def for_else(): def for_else():
"""
>>> for_else()
30
>>> print( 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
...@@ -19,5 +15,5 @@ def for_else(): ...@@ -19,5 +15,5 @@ def for_else():
def int_comp(): def int_comp():
cdef int i cdef int i
return tuple([ u"%02d" % i return u'*'.join(tuple([ u"%02d" % i
for i from 0 <= i < 3 ]) for i from 0 <= i < 3 ]))
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""" __doc__ = u"""
>>> index_tuple((1,1,2,3,5), 0) >>> index_object(100, 100)
1 Traceback (most recent call last):
>>> index_tuple((1,1,2,3,5), 3) ...
3 TypeError: 'int' object is unsubscriptable
>>> 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
...@@ -54,19 +11,65 @@ if sys.version_info[0] >= 3: ...@@ -54,19 +11,65 @@ if sys.version_info[0] >= 3:
elif sys.version_info < (2,5): 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
"""
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 +83,9 @@ def test_unsigned_long(): ...@@ -80,6 +83,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 +99,9 @@ def test_unsigned_short(): ...@@ -93,6 +99,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
This diff is collapsed.
...@@ -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
......
This diff is collapsed.
__doc__ = u""" __doc__ = u"""
>>> c_longs() >>> c_longs()
(1, 1L, -1L, 18446744073709551615L) (1, 1L, -1L, 18446744073709551615L)
>>> py_longs() >>> py_longs()
(1, 1L, 100000000000000000000000000000000L, -100000000000000000000000000000000L) (1, 1L, 100000000000000000000000000000000L, -100000000000000000000000000000000L)
""" """
import sys import sys
if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u'L', u'')
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'')
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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