Skip to content

Instantly share code, notes, and snippets.

@zed

zed/.gitignore Secret

Created February 23, 2011 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/6a01dc02e35fb04cf97d to your computer and use it in GitHub Desktop.
Save zed/6a01dc02e35fb04cf97d to your computer and use it in GitHub Desktop.
avoid duplicating default parameters in Cython
build/
pycode.cpp
pycode.so
// file: cppcode.cpp
#include "cppcode.hpp"
#include <iostream>
int init(const char *address, int port, bool en_msg, int error) {
using namespace std;
if (not address) return ++error;
std::cout << address << " "
<< port << " "
<< boolalpha << en_msg << " "
<< error << std::endl;
return error;
}
// file: cppcode.hpp
int init(const char *address=0, int port=0, bool en_msg=false, int error=0);
# file: cppcode.pxd
cdef extern from "cppcode.hpp":
int init(char *address, int port, bint en_msg, int error)
int init(char *address, int port, bint en_msg)
int init(char *address, int port)
int init(char *address)
int init()
# file: Makefile
.PHONY: test clean
test: pycode.so
python test_pycode.py
pycode.so: pycode.pyx setup.py cppcode.pxd cppcode.cpp cppcode.hpp
python setup.py build_ext -i
clean:
-rm *.so pycode.c* build/ -r
# file: pycode.pyx
cimport cppcode
class Unset(object):
def __nonzero__(self):
raise TypeError("a boolean is required")
UNSET = Unset()
def init(address=UNSET,port=UNSET,en_msg=UNSET,error=UNSET):
if error is not UNSET:
return cppcode.init(address, port, en_msg, error)
elif en_msg is not UNSET:
return cppcode.init(address, port, en_msg)
elif port is not UNSET:
return cppcode.init(address, port)
elif address is not UNSET:
return cppcode.init(address)
return cppcode.init()
# file: setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("pycode", ["pycode.pyx", "cppcode.cpp"],
language="c++",)] # libraries=["stdc++"])]
)
# file: test_pycode.py
"""
>>> pycode.init()
1
>>> pycode.init(port=123) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> pycode.init("address", port=123)
0
>>> pycode.init("address", 123, error=2) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> pycode.init("address", error=2) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
"""
import pycode
pycode.init("address")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment