summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
authorJohn Wiegley <johnw@newartisans.com>2008-08-05 13:17:04 -0400
committerJohn Wiegley <johnw@newartisans.com>2008-08-05 18:05:49 -0400
commitf6f4a46cf5b14f9a2170cd6475958efbf320caec (patch)
tree05bc1defcdebc201de3dd10477483d906a842821 /python
parentb7970b29855563e4c67f85af8b31233eda80c22a (diff)
downloadfork-ledger-f6f4a46cf5b14f9a2170cd6475958efbf320caec.tar.gz
fork-ledger-f6f4a46cf5b14f9a2170cd6475958efbf320caec.tar.bz2
fork-ledger-f6f4a46cf5b14f9a2170cd6475958efbf320caec.zip
Moved around most of the files so that source code is in src/, documentation
is in doc/, etc.
Diffstat (limited to 'python')
-rw-r--r--python/amounts.cc45
-rw-r--r--python/py_amount.cc320
-rw-r--r--python/py_commodity.cc63
-rw-r--r--python/py_times.cc132
-rw-r--r--python/py_utils.cc172
-rw-r--r--python/pyfstream.h203
-rw-r--r--python/pyinterp.cc239
-rw-r--r--python/pyinterp.h118
-rw-r--r--python/pyledger.cc46
-rw-r--r--python/pyledger.h47
-rw-r--r--python/pyutils.h112
-rwxr-xr-xpython/setup.py19
-rwxr-xr-xpython/test/PyUnitTests.py5
-rw-r--r--python/test/UnitTests.py9
-rw-r--r--python/test/__init__.py0
-rw-r--r--python/test/numerics/__init__.py0
-rw-r--r--python/test/numerics/t_amount.py1469
-rw-r--r--python/tuples.h281
18 files changed, 3280 insertions, 0 deletions
diff --git a/python/amounts.cc b/python/amounts.cc
new file mode 100644
index 00000000..ad3cda9a
--- /dev/null
+++ b/python/amounts.cc
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <boost/python.hpp>
+
+using namespace boost::python;
+
+void export_amount();
+void export_balance();
+void export_value();
+
+BOOST_PYTHON_MODULE(amounts)
+{
+ export_amount();
+ export_balance();
+ export_value();
+}
diff --git a/python/py_amount.cc b/python/py_amount.cc
new file mode 100644
index 00000000..16880f6f
--- /dev/null
+++ b/python/py_amount.cc
@@ -0,0 +1,320 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pyinterp.h"
+#include "pyutils.h"
+#include "amount.h"
+
+#include <boost/python/exception_translator.hpp>
+#include <boost/python/implicit.hpp>
+#include <boost/python/args.hpp>
+
+namespace ledger {
+
+using namespace boost::python;
+
+amount_t py_round_0(const amount_t& amount) {
+ return amount.round();
+}
+amount_t py_round_1(const amount_t& amount, amount_t::precision_t prec) {
+ return amount.round(prec);
+}
+
+double py_to_double_0(amount_t& amount) {
+ return amount.to_double();
+}
+double py_to_double_1(amount_t& amount, bool no_check) {
+ return amount.to_double(no_check);
+}
+
+long py_to_long_0(amount_t& amount) {
+ return amount.to_long();
+}
+long py_to_long_1(amount_t& amount, bool no_check) {
+ return amount.to_long(no_check);
+}
+
+boost::optional<amount_t> py_value_0(const amount_t& amount) {
+ return amount.value();
+}
+boost::optional<amount_t> py_value_1(const amount_t& amount,
+ const boost::optional<moment_t>& moment) {
+ return amount.value(moment);
+}
+
+void py_parse_2(amount_t& amount, object in, unsigned char flags) {
+ if (PyFile_Check(in.ptr())) {
+ pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
+ amount.parse(instr, flags);
+ } else {
+ PyErr_SetString(PyExc_IOError,
+ "Argument to amount.parse(file) is not a file object");
+ }
+}
+void py_parse_1(amount_t& amount, object in) {
+ py_parse_2(amount, in, 0);
+}
+
+void py_parse_str_1(amount_t& amount, const string& str) {
+ amount.parse(str);
+}
+void py_parse_str_2(amount_t& amount, const string& str, unsigned char flags) {
+ amount.parse(str, flags);
+}
+
+void py_read_1(amount_t& amount, object in) {
+ if (PyFile_Check(in.ptr())) {
+ pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
+ amount.read(instr);
+ } else {
+ PyErr_SetString(PyExc_IOError,
+ "Argument to amount.parse(file) is not a file object");
+ }
+}
+void py_read_2(amount_t& amount, const std::string& str) {
+ const char * p = str.c_str();
+ amount.read(p);
+}
+
+#define EXC_TRANSLATOR(type) \
+ void exc_translate_ ## type(const type& err) { \
+ PyErr_SetString(PyExc_ArithmeticError, err.what()); \
+ }
+
+EXC_TRANSLATOR(amount_error)
+
+void export_amount()
+{
+ scope().attr("AMOUNT_PARSE_NO_MIGRATE") = AMOUNT_PARSE_NO_MIGRATE;
+ scope().attr("AMOUNT_PARSE_NO_REDUCE") = AMOUNT_PARSE_NO_REDUCE;
+
+ class_< amount_t > ("amount")
+#if 0
+ .def("initialize", &amount_t::initialize)
+ .staticmethod("initialize")
+ .def("shutdown", &amount_t::shutdown)
+ .staticmethod("shutdown")
+#endif
+
+ .add_static_property("current_pool",
+ make_getter(&amount_t::current_pool,
+ return_value_policy<reference_existing_object>()))
+
+ .add_static_property("keep_base", &amount_t::keep_base)
+
+ .add_static_property("keep_price", &amount_t::keep_price)
+ .add_static_property("keep_date", &amount_t::keep_date)
+ .add_static_property("keep_tag", &amount_t::keep_tag)
+
+ .add_static_property("stream_fullstrings", &amount_t::stream_fullstrings)
+
+ .def(init<double>())
+ .def(init<long>())
+ .def(init<std::string>())
+
+ .def("exact", &amount_t::exact, args("value"),
+ "Construct an amount object whose display precision is always equal to its\n\
+internal precision.")
+ .staticmethod("exact")
+
+ .def(init<amount_t>())
+
+ .def("compare", &amount_t::compare)
+
+ .def(self == self)
+ .def(self == long())
+ .def(long() == self)
+ .def(self == double())
+ .def(double() == self)
+
+ .def(self != self)
+ .def(self != long())
+ .def(long() != self)
+ .def(self != double())
+ .def(double() != self)
+
+ .def(! self)
+
+ .def(self < self)
+ .def(self < long())
+ .def(long() < self)
+ .def(self < double())
+ .def(double() < self)
+
+ .def(self <= self)
+ .def(self <= long())
+ .def(long() <= self)
+ .def(self <= double())
+ .def(double() <= self)
+
+ .def(self > self)
+ .def(self > long())
+ .def(long() > self)
+ .def(self > double())
+ .def(double() > self)
+
+ .def(self >= self)
+ .def(self >= long())
+ .def(long() >= self)
+ .def(self >= double())
+ .def(double() >= self)
+
+ .def(self += self)
+ .def(self += long())
+ .def(self += double())
+
+ .def(self + self)
+ .def(self + long())
+ .def(long() + self)
+ .def(self + double())
+ .def(double() + self)
+
+ .def(self -= self)
+ .def(self -= long())
+ .def(self -= double())
+
+ .def(self - self)
+ .def(self - long())
+ .def(long() - self)
+ .def(self - double())
+ .def(double() - self)
+
+ .def(self *= self)
+ .def(self *= long())
+ .def(self *= double())
+
+ .def(self * self)
+ .def(self * long())
+ .def(long() * self)
+ .def(self * double())
+ .def(double() * self)
+
+ .def(self /= self)
+ .def(self /= long())
+ .def(self /= double())
+
+ .def(self / self)
+ .def(self / long())
+ .def(long() / self)
+ .def(self / double())
+ .def(double() / self)
+
+ .add_property("precision", &amount_t::precision)
+
+ .def("negate", &amount_t::negate)
+ .def("in_place_negate", &amount_t::in_place_negate,
+ return_value_policy<reference_existing_object>())
+ .def(- self)
+
+ .def("abs", &amount_t::abs)
+ .def("__abs__", &amount_t::abs)
+
+ .def("round", py_round_0)
+ .def("round", py_round_1)
+ .def("unround", &amount_t::unround)
+
+ .def("reduce", &amount_t::reduce)
+ .def("in_place_reduce", &amount_t::in_place_reduce,
+ return_value_policy<reference_existing_object>())
+
+ .def("unreduce", &amount_t::unreduce)
+ .def("in_place_unreduce", &amount_t::in_place_unreduce,
+ return_value_policy<reference_existing_object>())
+
+ .def("value", py_value_0)
+ .def("value", py_value_1)
+
+ .def("sign", &amount_t::sign)
+ .def("__nonzero__", &amount_t::is_nonzero)
+ .def("is_nonzero", &amount_t::is_nonzero)
+ .def("is_zero", &amount_t::is_zero)
+ .def("is_realzero", &amount_t::is_realzero)
+ .def("is_null", &amount_t::is_null)
+
+ .def("to_double", py_to_double_0)
+ .def("to_double", py_to_double_1)
+ .def("__float__", py_to_double_0)
+ .def("to_long", py_to_long_0)
+ .def("to_long", py_to_long_1)
+ .def("__int__", py_to_long_0)
+ .def("to_string", &amount_t::to_string)
+ .def("__str__", &amount_t::to_string)
+ .def("to_fullstring", &amount_t::to_fullstring)
+ .def("__repr__", &amount_t::to_fullstring)
+
+ .def("fits_in_double", &amount_t::fits_in_double)
+ .def("fits_in_long", &amount_t::fits_in_long)
+
+ .add_property("quantity_string", &amount_t::quantity_string)
+
+ .add_property("commodity",
+ make_function(&amount_t::commodity,
+ return_value_policy<reference_existing_object>()),
+ make_function(&amount_t::set_commodity,
+ with_custodian_and_ward<1, 2>()))
+
+ .def("has_commodity", &amount_t::has_commodity)
+ .def("clear_commodity", &amount_t::clear_commodity)
+ .add_property("number", &amount_t::number)
+
+ .def("annotate_commodity", &amount_t::annotate_commodity)
+ .def("commodity_annotated", &amount_t::commodity_annotated)
+ .add_property("annotation_details", &amount_t::annotation_details)
+ .def("strip_annotations", &amount_t::strip_annotations)
+
+ .def("parse", py_parse_1)
+ .def("parse", py_parse_2)
+ .def("parse", py_parse_str_1)
+ .def("parse", py_parse_str_2)
+
+ .def("parse_conversion", &amount_t::parse_conversion)
+ .staticmethod("parse_conversion")
+
+ .def("read", py_read_1)
+ .def("read", py_read_2)
+ .def("write", &amount_t::write)
+
+ .def("valid", &amount_t::valid)
+ ;
+
+ register_optional_to_python<amount_t>();
+
+ implicitly_convertible<double, amount_t>();
+ implicitly_convertible<long, amount_t>();
+ implicitly_convertible<string, amount_t>();
+
+#define EXC_TRANSLATE(type) \
+ register_exception_translator<type>(&exc_translate_ ## type);
+
+ EXC_TRANSLATE(amount_error);
+}
+
+} // namespace ledger
diff --git a/python/py_commodity.cc b/python/py_commodity.cc
new file mode 100644
index 00000000..3cf7d30c
--- /dev/null
+++ b/python/py_commodity.cc
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pyinterp.h"
+#include "pyutils.h"
+#include "amount.h"
+
+#include <boost/python/exception_translator.hpp>
+#include <boost/python/implicit.hpp>
+
+namespace ledger {
+
+using namespace boost::python;
+
+void export_commodity()
+{
+ scope().attr("COMMODITY_STYLE_DEFAULTS") = COMMODITY_STYLE_DEFAULTS;
+ scope().attr("COMMODITY_STYLE_SUFFIXED") = COMMODITY_STYLE_SUFFIXED;
+ scope().attr("COMMODITY_STYLE_SEPARATED") = COMMODITY_STYLE_SEPARATED;
+ scope().attr("COMMODITY_STYLE_EUROPEAN") = COMMODITY_STYLE_EUROPEAN;
+ scope().attr("COMMODITY_STYLE_THOUSANDS") = COMMODITY_STYLE_THOUSANDS;
+ scope().attr("COMMODITY_STYLE_NOMARKET") = COMMODITY_STYLE_NOMARKET;
+ scope().attr("COMMODITY_STYLE_BUILTIN") = COMMODITY_STYLE_BUILTIN;
+
+ class_< commodity_t, bases<>,
+ commodity_t, boost::noncopyable > ("commodity", no_init)
+ .def(self == self)
+
+ .def("drop_flags", &commodity_t::drop_flags)
+
+ .add_property("precision", &commodity_t::precision)
+ ;
+}
+
+} // namespace ledger
diff --git a/python/py_times.cc b/python/py_times.cc
new file mode 100644
index 00000000..00108b04
--- /dev/null
+++ b/python/py_times.cc
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pyinterp.h"
+#include "pyutils.h"
+
+#include <boost/cast.hpp>
+#include <boost/python/module.hpp>
+#include <boost/python/def.hpp>
+#include <boost/python/to_python_converter.hpp>
+
+#include <Python.h>
+#include <datetime.h>
+
+// jww (2007-05-04): Convert time duration objects to PyDelta
+
+namespace ledger {
+
+using namespace boost::python;
+
+typedef boost::gregorian::date date;
+
+struct date_to_python
+{
+ static PyObject* convert(const date& dte)
+ {
+ PyDateTime_IMPORT;
+ return PyDate_FromDate(dte.year(), dte.month(), dte.day());
+ }
+};
+
+struct date_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ PyDateTime_IMPORT;
+ if (PyDate_Check(obj_ptr)) return obj_ptr;
+ return 0;
+ }
+
+ static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
+ {
+ PyDateTime_IMPORT;
+ int y = PyDateTime_GET_YEAR(obj_ptr);
+ int m = PyDateTime_GET_MONTH(obj_ptr);
+ int d = PyDateTime_GET_DAY(obj_ptr);
+ date* dte = new date(y,m,d);
+ data->convertible = (void*)dte;
+ }
+};
+
+typedef register_python_conversion<date, date_to_python, date_from_python>
+ date_python_conversion;
+
+
+struct datetime_to_python
+{
+ static PyObject* convert(const moment_t& moment)
+ {
+ PyDateTime_IMPORT;
+ date dte = moment.date();
+ moment_t::time_duration_type tod = moment.time_of_day();
+ return PyDateTime_FromDateAndTime(dte.year(), dte.month(), dte.day(),
+ tod.hours(), tod.minutes(), tod.seconds(),
+ tod.total_microseconds() % 1000000);
+ }
+};
+
+struct datetime_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ PyDateTime_IMPORT;
+ if(PyDateTime_Check(obj_ptr)) return obj_ptr;
+ return 0;
+ }
+
+ static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
+ {
+ PyDateTime_IMPORT;
+ int y = PyDateTime_GET_YEAR(obj_ptr);
+ int m = PyDateTime_GET_MONTH(obj_ptr);
+ int d = PyDateTime_GET_DAY(obj_ptr);
+ int h = PyDateTime_DATE_GET_HOUR(obj_ptr);
+ int min = PyDateTime_DATE_GET_MINUTE(obj_ptr);
+ int s = PyDateTime_DATE_GET_SECOND(obj_ptr);
+ moment_t* moment = new moment_t(date(y,m,d),
+ moment_t::time_duration_type(h, min, s));
+ data->convertible = (void*)moment;
+ }
+};
+
+typedef register_python_conversion<moment_t, datetime_to_python, datetime_from_python>
+ datetime_python_conversion;
+
+void export_times()
+{
+ date_python_conversion();
+ datetime_python_conversion();
+
+ register_optional_to_python<moment_t>();
+}
+
+} // namespace ledger
diff --git a/python/py_utils.cc b/python/py_utils.cc
new file mode 100644
index 00000000..9fc375f6
--- /dev/null
+++ b/python/py_utils.cc
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pyinterp.h"
+#include "pyutils.h"
+
+#include <boost/python/module.hpp>
+#include <boost/python/def.hpp>
+#include <boost/python/to_python_converter.hpp>
+
+namespace ledger {
+
+using namespace boost::python;
+
+struct bool_to_python
+{
+ static PyObject * convert(const bool truth)
+ {
+ if (truth)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
+ }
+};
+
+struct bool_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ if (!PyBool_Check(obj_ptr)) return 0;
+ return obj_ptr;
+ }
+
+ static void construct(PyObject* obj_ptr,
+ converter::rvalue_from_python_stage1_data* data)
+ {
+ void* storage = ((converter::rvalue_from_python_storage<bool>*) data)->storage.bytes;
+ if (obj_ptr == Py_True)
+ new (storage) bool(true);
+ else
+ new (storage) bool(false);
+ data->convertible = storage;
+ }
+};
+
+typedef register_python_conversion<bool, bool_to_python, bool_from_python>
+ bool_python_conversion;
+
+
+struct string_to_python
+{
+ static PyObject* convert(const string& str)
+ {
+ return incref(object(*boost::polymorphic_downcast<const std::string *>(&str)).ptr());
+ }
+};
+
+struct string_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ if (!PyString_Check(obj_ptr)) return 0;
+ return obj_ptr;
+ }
+
+ static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
+ {
+ const char* value = PyString_AsString(obj_ptr);
+ if (value == 0) throw_error_already_set();
+ void* storage = ((converter::rvalue_from_python_storage<string>*) data)->storage.bytes;
+ new (storage) string(value);
+ data->convertible = storage;
+ }
+};
+
+typedef register_python_conversion<string, string_to_python, string_from_python>
+ string_python_conversion;
+
+
+struct istream_to_python
+{
+ static PyObject* convert(const std::istream& str)
+ {
+ return incref(boost::python::detail::none());
+ }
+};
+
+struct istream_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ if (!PyFile_Check(obj_ptr)) return 0;
+ return obj_ptr;
+ }
+
+ static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
+ {
+ void* storage = ((converter::rvalue_from_python_storage<pyifstream>*) data)->storage.bytes;
+ new (storage) pyifstream(reinterpret_cast<PyFileObject *>(obj_ptr));
+ data->convertible = storage;
+ }
+};
+
+typedef register_python_conversion<std::istream, istream_to_python, istream_from_python>
+ istream_python_conversion;
+
+
+struct ostream_to_python
+{
+ static PyObject* convert(const std::ostream& str)
+ {
+ return incref(boost::python::detail::none());
+ }
+};
+
+struct ostream_from_python
+{
+ static void* convertible(PyObject* obj_ptr)
+ {
+ if (!PyFile_Check(obj_ptr)) return 0;
+ return obj_ptr;
+ }
+
+ static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
+ {
+ void* storage = ((converter::rvalue_from_python_storage<pyofstream>*) data)->storage.bytes;
+ new (storage) pyofstream(reinterpret_cast<PyFileObject *>(obj_ptr));
+ data->convertible = storage;
+ }
+};
+
+typedef register_python_conversion<std::ostream, ostream_to_python, ostream_from_python>
+ ostream_python_conversion;
+
+
+void export_utils()
+{
+ bool_python_conversion();
+ string_python_conversion();
+ istream_python_conversion();
+ ostream_python_conversion();
+}
+
+} // namespace ledger
diff --git a/python/pyfstream.h b/python/pyfstream.h
new file mode 100644
index 00000000..1d72d471
--- /dev/null
+++ b/python/pyfstream.h
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _PYFSTREAM_H
+#define _PYFSTREAM_H
+
+// pyofstream
+// - a stream that writes on a Python file object
+
+class pyoutbuf : public boost::noncopyable, public std::streambuf
+{
+ pyoutbf();
+
+protected:
+ PyFileObject * fo; // Python file object
+
+public:
+ // constructor
+ pyoutbuf(PyFileObject * _fo) : fo(_fo) {
+ TRACE_CTOR(pyoutbuf, "PyFileObject *");
+ }
+ ~pyoutbuf() : throw() {
+ TRACE_DTOR(pyoutbuf);
+ }
+
+protected:
+ // write one character
+ virtual int_type overflow (int_type c) {
+ if (c != EOF) {
+ char z[2];
+ z[0] = c;
+ z[1] = '\0';
+ if (PyFile_WriteString(z, (PyObject *)fo) < 0) {
+ return EOF;
+ }
+ }
+ return c;
+ }
+
+ // write multiple characters
+ virtual std::streamsize xsputn (const char* s, std::streamsize num) {
+ char * buf = new char[num + 1];
+ std::strncpy(buf, s, num);
+ buf[num] = '\0';
+ if (PyFile_WriteString(buf, (PyObject *)fo) < 0)
+ num = 0;
+ checked_array_delete(buf);
+ return num;
+ }
+};
+
+class pyofstream : public noncopyable, public std::ostream
+{
+ pyofstream();
+
+protected:
+ pyoutbuf buf;
+
+public:
+ pyofstream (PyFileObject * fo) : std::ostream(0), buf(fo) {
+ TRACE_CTOR(pyofstream, "PyFileObject *");
+ rdbuf(&buf);
+ }
+ ~pyofstream() throw() {
+ TRACE_DTOR(pyofstream);
+ }
+};
+
+// pyifstream
+// - a stream that reads on a file descriptor
+
+class pyinbuf : public noncopyable, public std::streambuf
+{
+ pyinbuf();
+
+protected:
+ PyFileObject * fo; // Python file object
+
+protected:
+ /* data buffer:
+ * - at most, pbSize characters in putback area plus
+ * - at most, bufSize characters in ordinary read buffer
+ */
+ static const int pbSize = 4; // size of putback area
+ static const int bufSize = 1024; // size of the data buffer
+ char buffer[bufSize + pbSize]; // data buffer
+
+public:
+ /* constructor
+ * - initialize file descriptor
+ * - initialize empty data buffer
+ * - no putback area
+ * => force underflow()
+ */
+ pyinbuf (PyFileObject * _fo) : fo(_fo) {
+ TRACE_CTOR(pyinbuf, "PyFileObject *");
+
+ setg (buffer+pbSize, // beginning of putback area
+ buffer+pbSize, // read position
+ buffer+pbSize); // end position
+ }
+ ~pyinbuf() throw() {
+ TRACE_DTOR(pyinbuf);
+ }
+
+protected:
+ // insert new characters into the buffer
+ virtual int_type underflow () {
+#ifndef _MSC_VER
+ using std::memmove;
+#endif
+
+ // is read position before end of buffer?
+ if (gptr() < egptr()) {
+ return traits_type::to_int_type(*gptr());
+ }
+
+ /* process size of putback area
+ * - use number of characters read
+ * - but at most size of putback area
+ */
+ int numPutback;
+ numPutback = gptr() - eback();
+ if (numPutback > pbSize) {
+ numPutback = pbSize;
+ }
+
+ /* copy up to pbSize characters previously read into
+ * the putback area
+ */
+ memmove (buffer+(pbSize-numPutback), gptr()-numPutback,
+ numPutback);
+
+ // read at most bufSize new characters
+ int num;
+ PyObject *line = PyFile_GetLine((PyObject *)fo, bufSize);
+ if (! line || ! PyString_Check(line)) {
+ // ERROR or EOF
+ return EOF;
+ }
+
+ num = PyString_Size(line);
+ if (num == 0)
+ return EOF;
+
+ memmove (buffer+pbSize, PyString_AsString(line), num);
+
+ // reset buffer pointers
+ setg (buffer+(pbSize-numPutback), // beginning of putback area
+ buffer+pbSize, // read position
+ buffer+pbSize+num); // end of buffer
+
+ // return next character
+ return traits_type::to_int_type(*gptr());
+ }
+};
+
+class pyifstream : public noncopyable, public std::istream
+{
+ pyifstream();
+
+protected:
+ pyinbuf buf;
+
+public:
+ pyifstream (PyFileObject * fo) : std::istream(0), buf(fo) {
+ TRACE_CTOR(pyifstream, "PyFileObject *");
+ rdbuf(&buf);
+ }
+ ~pyifstream() throw() {
+ TRACE_DTOR(pyifstream);
+ }
+};
+
+#endif // _PYFSTREAM_H
diff --git a/python/pyinterp.cc b/python/pyinterp.cc
new file mode 100644
index 00000000..07a619fe
--- /dev/null
+++ b/python/pyinterp.cc
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pyinterp.h"
+
+#include <boost/python/module_init.hpp>
+
+namespace ledger {
+
+using namespace boost::python;
+
+void export_utils();
+void export_times();
+void export_amount();
+void export_commodity();
+#if 0
+void export_balance();
+void export_value();
+void export_journal();
+void export_parser();
+void export_option();
+void export_walk();
+void export_report();
+void export_format();
+void export_valexpr();
+#endif
+
+void initialize_for_python()
+{
+ export_utils();
+ export_times();
+ export_amount();
+ export_commodity();
+#if 0
+ export_balance();
+ export_value();
+ export_journal();
+ export_parser();
+ export_option();
+ export_walk();
+ export_format();
+ export_report();
+ export_valexpr();
+#endif
+}
+
+struct python_run
+{
+ object result;
+
+ python_run(python_interpreter_t * intepreter,
+ const string& str, int input_mode)
+ : result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode,
+ intepreter->nspace.ptr(),
+ intepreter->nspace.ptr())))) {}
+ operator object() {
+ return result;
+ }
+};
+
+python_interpreter_t::python_interpreter_t()
+ : scope_t(), mmodule(borrowed(PyImport_AddModule("__main__"))),
+ nspace(handle<>(borrowed(PyModule_GetDict(mmodule.get()))))
+{
+ TRACE_CTOR(python_interpreter_t, "expr_t::scope_t&");
+
+ Py_Initialize();
+ boost::python::detail::init_module("ledger", &initialize_for_python);
+}
+
+object python_interpreter_t::import(const string& str)
+{
+ assert(Py_IsInitialized());
+
+ try {
+ PyObject * mod = PyImport_Import(PyString_FromString(str.c_str()));
+ if (! mod)
+ throw_(std::logic_error, "Failed to import Python module " << str);
+
+ object newmod(handle<>(borrowed(mod)));
+
+#if 1
+ // Import all top-level entries directly into the main namespace
+ dict m_nspace(handle<>(borrowed(PyModule_GetDict(mod))));
+ nspace.update(m_nspace);
+#else
+ nspace[string(PyModule_GetName(mod))] = newmod;
+#endif
+ return newmod;
+ }
+ catch (const error_already_set&) {
+ PyErr_Print();
+ throw_(std::logic_error, "Importing Python module " << str);
+ }
+ return object();
+}
+
+object python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode)
+{
+ bool first = true;
+ string buffer;
+ buffer.reserve(4096);
+
+ while (! in.eof()) {
+ char buf[256];
+ in.getline(buf, 255);
+ if (buf[0] == '!')
+ break;
+ if (first)
+ first = false;
+ else
+ buffer += "\n";
+ buffer += buf;
+ }
+
+ try {
+ int input_mode;
+ switch (mode) {
+ case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
+ case PY_EVAL_STMT: input_mode = Py_single_input; break;
+ case PY_EVAL_MULTI: input_mode = Py_file_input; break;
+ }
+ assert(Py_IsInitialized());
+ return python_run(this, buffer, input_mode);
+ }
+ catch (const error_already_set&) {
+ PyErr_Print();
+ throw_(std::logic_error, "Evaluating Python code");
+ }
+ return object();
+}
+
+object python_interpreter_t::eval(const string& str, py_eval_mode_t mode)
+{
+ try {
+ int input_mode;
+ switch (mode) {
+ case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
+ case PY_EVAL_STMT: input_mode = Py_single_input; break;
+ case PY_EVAL_MULTI: input_mode = Py_file_input; break;
+ }
+ assert(Py_IsInitialized());
+ return python_run(this, str, input_mode);
+ }
+ catch (const error_already_set&) {
+ PyErr_Print();
+ throw_(std::logic_error, "Evaluating Python code");
+ }
+ return object();
+}
+
+value_t python_interpreter_t::functor_t::operator()
+ (expr_t::call_scope_t& args)
+{
+ try {
+ if (! PyCallable_Check(func.ptr())) {
+ return extract<value_t>(func.ptr());
+ } else {
+ if (args.size() > 0) {
+ list arglist;
+ if (args.value().is_sequence())
+ foreach (const value_t& value, args.value().as_sequence())
+ arglist.append(value);
+ else
+ arglist.append(args.value());
+
+ if (PyObject * val =
+ PyObject_CallObject(func.ptr(),
+ boost::python::tuple(arglist).ptr())) {
+ value_t result = extract<value_t>(val)();
+ Py_DECREF(val);
+ return result;
+ }
+ else if (PyObject * err = PyErr_Occurred()) {
+ PyErr_Print();
+ throw_(expr_t::calc_error,
+ "While calling Python function '" /*<< name() <<*/ "': " << err);
+ } else {
+ assert(false);
+ }
+ } else {
+ return call<value_t>(func.ptr());
+ }
+ }
+ }
+ catch (const error_already_set&) {
+ PyErr_Print();
+ throw_(expr_t::calc_error,
+ "While calling Python function '" /*<< name() <<*/ "'");
+ }
+ return NULL_VALUE;
+}
+
+value_t python_interpreter_t::lambda_t::operator()
+ (expr_t::call_scope_t& args)
+{
+ try {
+ assert(args.size() == 1);
+ value_t item = args[0];
+ assert(item.is_xml_node());
+ return call<value_t>(func.ptr(), item.as_xml_node());
+ }
+ catch (const error_already_set&) {
+ PyErr_Print();
+ throw_(expr_t::calc_error,
+ "While evaluating Python lambda expression");
+ }
+ return NULL_VALUE;
+}
+
+} // namespace ledger
diff --git a/python/pyinterp.h b/python/pyinterp.h
new file mode 100644
index 00000000..5486eea5
--- /dev/null
+++ b/python/pyinterp.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _PYINTERP_H
+#define _PYINTERP_H
+
+#include "scope.h"
+
+#include <boost/python.hpp>
+#include <Python.h>
+
+namespace ledger {
+
+class python_interpreter_t : public noncopyable, public scope_t
+{
+ boost::python::handle<> mmodule;
+
+ python_interpreter_t();
+
+public:
+ boost::python::dict nspace;
+
+ python_interpreter_t(expr_t::scope_t& parent);
+
+ virtual ~python_interpreter_t() {
+ TRACE_DTOR(python_interpreter_t);
+
+ Py_Finalize();
+ }
+
+ boost::python::object import(const string& name);
+
+ enum py_eval_mode_t {
+ PY_EVAL_EXPR,
+ PY_EVAL_STMT,
+ PY_EVAL_MULTI
+ };
+
+ boost::python::object eval(std::istream& in,
+ py_eval_mode_t mode = PY_EVAL_EXPR);
+ boost::python::object eval(const string& str,
+ py_eval_mode_t mode = PY_EVAL_EXPR);
+ boost::python::object eval(const char * c_str,
+ py_eval_mode_t mode = PY_EVAL_EXPR) {
+ string str(c_str);
+ return eval(str, mode);
+ }
+
+ class functor_t {
+ functor_t();
+ protected:
+ boost::python::object func;
+ public:
+ functor_t(const string& name, boost::python::object _func) : func(_func) {
+ TRACE_CTOR(functor_t, "const string&, boost::python::object");
+ }
+ functor_t(const functor_t& other) : func(other.func) {
+ TRACE_CTOR(functor_t, "copy");
+ }
+ virtual ~functor_t() throw() {
+ TRACE_DTOR(functor_t);
+ }
+ virtual value_t operator()(expr_t::call_scope_t& args);
+ };
+
+ virtual expr_t::ptr_op_t lookup(const string& name) {
+ if (boost::python::object func = eval(name))
+ return WRAP_FUNCTOR(functor_t(name, func));
+ return expr_t::ptr_op_t();
+ }
+
+ class lambda_t : public functor_t {
+ lambda_t();
+ public:
+ lambda_t(boost::python::object code) : functor_t("<lambda>", code) {
+ TRACE_CTOR(functor_t, "boost::python::object");
+ }
+ lambda_t(const lambda_t& other) : functor_t(other) {
+ TRACE_CTOR(lambda_t, "copy");
+ }
+ virtual ~lambda_t() throw() {
+ TRACE_DTOR(lambda_t);
+ }
+ virtual value_t operator()(expr_t::call_scope_t& args);
+ };
+};
+
+} // namespace ledger
+
+#endif // _PYINTERP_H
diff --git a/python/pyledger.cc b/python/pyledger.cc
new file mode 100644
index 00000000..76d7ab0c
--- /dev/null
+++ b/python/pyledger.cc
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <pyledger.h>
+
+using namespace boost::python;
+
+ledger::session_t python_session;
+
+namespace ledger {
+ extern void initialize_for_python();
+}
+
+BOOST_PYTHON_MODULE(ledger)
+{
+ ledger::set_session_context(&python_session);
+ ledger::initialize_for_python();
+}
diff --git a/python/pyledger.h b/python/pyledger.h
new file mode 100644
index 00000000..a298cc05
--- /dev/null
+++ b/python/pyledger.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _PYLEDGER_H
+#define _PYLEDGER_H
+
+//////////////////////////////////////////////////////////////////////
+//
+// Ledger Accounting Tool (with Python support via Boost.Python)
+//
+// A command-line tool for general double-entry accounting.
+//
+// Copyright (c) 2003,2004 John Wiegley <johnw@newartisans.com>
+//
+
+#include <ledger.h>
+#include <pyinterp.h>
+
+#endif // _PYLEDGER_H
diff --git a/python/pyutils.h b/python/pyutils.h
new file mode 100644
index 00000000..bdb1f142
--- /dev/null
+++ b/python/pyutils.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _PY_UTILS_H
+#define _PY_UTILS_H
+
+#include "pyfstream.h"
+
+template <typename T, typename TfromPy>
+struct object_from_python
+{
+ object_from_python() {
+ boost::python::converter::registry::push_back
+ (&TfromPy::convertible, &TfromPy::construct,
+ boost::python::type_id<T>());
+ }
+};
+
+template <typename T, typename TtoPy, typename TfromPy>
+struct register_python_conversion
+{
+ register_python_conversion() {
+ boost::python::to_python_converter<T, TtoPy>();
+ object_from_python<T, TfromPy>();
+ }
+};
+
+template <typename T>
+struct register_optional_to_python : public boost::noncopyable
+{
+ struct optional_to_python
+ {
+ static PyObject * convert(const boost::optional<T>& value)
+ {
+ return boost::python::incref
+ (value ? boost::python::to_python_value<T>()(*value) :
+ boost::python::detail::none());
+ }
+ };
+
+ struct optional_from_python
+ {
+ static void * convertible(PyObject * source)
+ {
+ using namespace boost::python::converter;
+
+ if (source == Py_None)
+ return source;
+
+ const registration& converters(registered<T>::converters);
+
+ if (implicit_rvalue_convertible_from_python(source, converters)) {
+ rvalue_from_python_stage1_data data =
+ rvalue_from_python_stage1(source, converters);
+ return rvalue_from_python_stage2(source, data, converters);
+ }
+ return NULL;
+ }
+
+ static void construct(PyObject * source,
+ boost::python::converter::rvalue_from_python_stage1_data * data)
+ {
+ using namespace boost::python::converter;
+
+ void * const storage = ((rvalue_from_python_storage<T> *) data)->storage.bytes;
+
+ if (data->convertible == source) // == None
+ new (storage) boost::optional<T>(); // A Boost uninitialized value
+ else
+ new (storage) boost::optional<T>(*static_cast<T *>(data->convertible));
+
+ data->convertible = storage;
+ }
+ };
+
+ explicit register_optional_to_python() {
+ register_python_conversion<boost::optional<T>,
+ optional_to_python, optional_from_python>();
+ }
+};
+
+//boost::python::register_ptr_to_python< boost::shared_ptr<Base> >();
+
+#endif // _PY_UTILS_H
diff --git a/python/setup.py b/python/setup.py
new file mode 100755
index 00000000..4413a88d
--- /dev/null
+++ b/python/setup.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+
+from distutils.core import setup, Extension
+
+import os
+
+defines = [('PYTHON_MODULE', 1)]
+libs = os.environ["PYLIBS"].split()
+
+setup(name = "Ledger",
+ version = "2.7",
+ description = "Ledger Accounting Library",
+ author = "John Wiegley",
+ author_email = "johnw@newartisans.com",
+ url = "http://www.newartisans.com/software/ledger.html",
+ ext_modules = [
+ Extension("ledger",
+ [os.path.join(os.environ['SRCDIR'], "pyledger.cc")],
+ define_macros = defines, libraries = libs)])
diff --git a/python/test/PyUnitTests.py b/python/test/PyUnitTests.py
new file mode 100755
index 00000000..3c19093f
--- /dev/null
+++ b/python/test/PyUnitTests.py
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+PYTHONPATH="%builddir%":"%srcdir%":$PYTHONPATH \
+DYLD_LIBRARY_PATH="%builddir%/.libs":"%builddir%/gdtoa/.libs":$DYLD_LIBRARY_PATH \
+ python "%srcdir%"/tests/python/UnitTests.py
diff --git a/python/test/UnitTests.py b/python/test/UnitTests.py
new file mode 100644
index 00000000..843e9fc1
--- /dev/null
+++ b/python/test/UnitTests.py
@@ -0,0 +1,9 @@
+from unittest import TextTestRunner, TestSuite
+
+import tests.python.numerics.t_amount as t_amount
+
+suites = [
+ t_amount.suite(),
+]
+
+TextTestRunner().run(TestSuite(suites))
diff --git a/python/test/__init__.py b/python/test/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/python/test/__init__.py
diff --git a/python/test/numerics/__init__.py b/python/test/numerics/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/python/test/numerics/__init__.py
diff --git a/python/test/numerics/t_amount.py b/python/test/numerics/t_amount.py
new file mode 100644
index 00000000..95c98bdb
--- /dev/null
+++ b/python/test/numerics/t_amount.py
@@ -0,0 +1,1469 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+import exceptions
+import operator
+
+from ledger import *
+from StringIO import *
+
+internalAmount = amount.exact
+
+class t_amountTestCase(unittest.TestCase):
+ testSession = None
+
+ def assertValid(self, amt):
+ self.assertTrue(amt.valid())
+
+ def setUp(self):
+ self.testSession = session()
+ set_session_context(self.testSession)
+
+ # Cause the display precision for dollars to be initialized to 2.
+ x1 = amount("$1.00")
+ self.assertTrue(x1)
+
+ amount.stream_fullstrings = True # make reports from UnitTests accurate
+
+ def tearDown(self):
+ amount.stream_fullstrings = False
+
+ set_session_context()
+ self.testSession = None
+
+ def testParser(self):
+ x0 = amount()
+ x1 = amount()
+ x2 = amount()
+ x3 = amount()
+ x4 = amount(123.456)
+ x5 = amount(x4)
+ x6 = amount(x4)
+ x7 = amount(x4)
+ x8 = amount("$123.45")
+ x9 = amount(x8)
+ x10 = amount(x8)
+ x11 = amount(x8)
+ x12 = amount("$100")
+
+ self.assertEqual(2, x12.commodity.precision)
+
+ #buf = "$100..."
+ #input = StringIO(buf)
+ #x13 = amount()
+ #x13.parse(input)
+ #self.assertEqual(x12, x13)
+
+ x14 = amount()
+ self.assertRaises(exceptions.ArithmeticError, lambda: x14.parse("DM"))
+
+ x15 = amount("$1.000.000,00")
+
+ x16 = amount("$2000")
+ self.assertEqual("$2.000,00", x16.to_string())
+ x16.parse("$2000,00")
+ self.assertEqual("$2.000,00", x16.to_string())
+
+ # Since European-ness is an additive quality, we must switch back
+ # to American-ness manually
+ x15.commodity.drop_flags(COMMODITY_STYLE_EUROPEAN)
+
+ x17 = amount("$1,000,000.00")
+
+ x18 = amount("$2000")
+ self.assertEqual("$2,000.00", x18.to_string())
+ x18.parse("$2,000")
+ self.assertEqual("$2,000.00", x18.to_string())
+
+ self.assertEqual(x15, x17)
+
+ x19 = amount("EUR 1000")
+ x20 = amount("EUR 1000")
+
+ self.assertEqual("EUR 1000", x19.to_string())
+ self.assertEqual("EUR 1000", x20.to_string())
+
+ x1.parse("$100.0000", AMOUNT_PARSE_NO_MIGRATE)
+ self.assertEqual(2, x12.commodity.precision)
+ self.assertEqual(x1.commodity, x12.commodity)
+ self.assertEqual(x1, x12)
+
+ x0.parse("$100.0000")
+ self.assertEqual(4, x12.commodity.precision)
+ self.assertEqual(x0.commodity, x12.commodity)
+ self.assertEqual(x0, x12)
+
+ x2.parse("$100.00", AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x2, x12)
+ x3.parse("$100.00", AMOUNT_PARSE_NO_MIGRATE | AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x3, x12)
+
+ x4.parse("$100.00")
+ self.assertEqual(x4, x12)
+ x5.parse("$100.00", AMOUNT_PARSE_NO_MIGRATE)
+ self.assertEqual(x5, x12)
+ x6.parse("$100.00", AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x6, x12)
+ x7.parse("$100.00", AMOUNT_PARSE_NO_MIGRATE | AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x7, x12)
+
+ x8.parse("$100.00")
+ self.assertEqual(x8, x12)
+ x9.parse("$100.00", AMOUNT_PARSE_NO_MIGRATE)
+ self.assertEqual(x9, x12)
+ x10.parse("$100.00", AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x10, x12)
+ x11.parse("$100.00", AMOUNT_PARSE_NO_MIGRATE | AMOUNT_PARSE_NO_REDUCE)
+ self.assertEqual(x11, x12)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+ self.assertValid(x11)
+ self.assertValid(x12)
+
+ def testConstructors(self):
+ x0 = amount()
+ x1 = amount(123456)
+ x2 = amount(123456L)
+ x3 = amount(123.456)
+ x5 = amount("123456")
+ x6 = amount("123.456")
+ x7 = amount("123456")
+ x8 = amount("123.456")
+ x9 = amount(x3)
+ x10 = amount(x6)
+ x11 = amount(x8)
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: amount(0) == x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: amount() == x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: amount("0") == x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: amount("0.0") == x0)
+ self.assertEqual(x2, x1)
+ self.assertEqual(x5, x1)
+ self.assertEqual(x7, x1)
+ self.assertEqual(x6, x3)
+ self.assertEqual(x8, x3)
+ self.assertEqual(x10, x3)
+ self.assertEqual(x10, x9)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+ self.assertValid(x11)
+
+ def testCommodityConstructors(self):
+ x1 = amount("$123.45")
+ x2 = amount("-$123.45")
+ x3 = amount("$-123.45")
+ x4 = amount("DM 123.45")
+ x5 = amount("-DM 123.45")
+ x6 = amount("DM -123.45")
+ x7 = amount("123.45 euro")
+ x8 = amount("-123.45 euro")
+ x9 = amount("123.45€")
+ x10 = amount("-123.45€")
+
+ self.assertEqual(amount("$123.45"), x1)
+ self.assertEqual(amount("-$123.45"), x2)
+ self.assertEqual(amount("$-123.45"), x3)
+ self.assertEqual(amount("DM 123.45"), x4)
+ self.assertEqual(amount("-DM 123.45"), x5)
+ self.assertEqual(amount("DM -123.45"), x6)
+ self.assertEqual(amount("123.45 euro"), x7)
+ self.assertEqual(amount("-123.45 euro"), x8)
+ self.assertEqual(amount("123.45€"), x9)
+ self.assertEqual(amount("-123.45€"), x10)
+
+ self.assertEqual("$123.45", x1.to_string())
+ self.assertEqual("$-123.45", x2.to_string())
+ self.assertEqual("$-123.45", x3.to_string())
+ self.assertEqual("DM 123.45", x4.to_string())
+ self.assertEqual("DM -123.45", x5.to_string())
+ self.assertEqual("DM -123.45", x6.to_string())
+ self.assertEqual("123.45 euro", x7.to_string())
+ self.assertEqual("-123.45 euro", x8.to_string())
+ self.assertEqual("123.45€", x9.to_string())
+ self.assertEqual("-123.45€", x10.to_string())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testAssignment(self):
+ x0 = amount()
+ x1 = amount(123456)
+ x2 = amount(123456L)
+ x3 = amount(123.456)
+ x5 = amount("123456")
+ x6 = amount("123.456")
+ x7 = "123456"
+ x8 = "123.456"
+ x9 = amount(x3)
+ x10 = amount(x6)
+
+ self.assertEqual(x2, x1)
+ self.assertEqual(x5, x1)
+ self.assertEqual(x7, x1)
+ self.assertEqual(x6, x3)
+ self.assertEqual(x8, x3)
+ self.assertEqual(x10, x3)
+ self.assertEqual(x10, x9)
+
+ x1 = amount(123456)
+ x2 = amount(123456L)
+ x3 = amount(123.456)
+ x5 = amount("123456")
+ x6 = amount("123.456")
+ x7 = amount("123456")
+ x8 = amount("123.456")
+ x9 = x3
+ x10 = amount(x6)
+
+ self.assertEqual(x2, x1)
+ self.assertEqual(x5, x1)
+ self.assertEqual(x7, x1)
+ self.assertEqual(x6, x3)
+ self.assertEqual(x8, x3)
+ self.assertEqual(x10, x3)
+ self.assertEqual(x10, x9)
+
+ self.assertFalse(x1.is_null())
+ x1 = x0 # sets x1 back to uninitialized state
+ self.assertTrue(x0.is_null())
+ self.assertTrue(x1.is_null())
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testCommodityAssignment(self):
+ x1 = amount("$123.45")
+ x2 = amount("-$123.45")
+ x3 = amount("$-123.45")
+ x4 = amount("DM 123.45")
+ x5 = amount("-DM 123.45")
+ x6 = amount("DM -123.45")
+ x7 = amount("123.45 euro")
+ x8 = amount("-123.45 euro")
+ x9 = amount("123.45€")
+ x10 = amount("-123.45€")
+
+ self.assertEqual(amount("$123.45"), x1)
+ self.assertEqual(amount("-$123.45"), x2)
+ self.assertEqual(amount("$-123.45"), x3)
+ self.assertEqual(amount("DM 123.45"), x4)
+ self.assertEqual(amount("-DM 123.45"), x5)
+ self.assertEqual(amount("DM -123.45"), x6)
+ self.assertEqual(amount("123.45 euro"), x7)
+ self.assertEqual(amount("-123.45 euro"), x8)
+ self.assertEqual(amount("123.45€"), x9)
+ self.assertEqual(amount("-123.45€"), x10)
+
+ self.assertEqual("$123.45", x1.to_string())
+ self.assertEqual("$-123.45", x2.to_string())
+ self.assertEqual("$-123.45", x3.to_string())
+ self.assertEqual("DM 123.45", x4.to_string())
+ self.assertEqual("DM -123.45", x5.to_string())
+ self.assertEqual("DM -123.45", x6.to_string())
+ self.assertEqual("123.45 euro", x7.to_string())
+ self.assertEqual("-123.45 euro", x8.to_string())
+ self.assertEqual("123.45€", x9.to_string())
+ self.assertEqual("-123.45€", x10.to_string())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testEquality(self):
+ x1 = amount(123456)
+ x2 = amount(456789)
+ x3 = amount(333333)
+ x4 = amount(123456.0)
+ x5 = amount("123456.0")
+ x6 = amount(123456.0)
+
+ self.assertTrue(x1 == 123456)
+ self.assertTrue(x1 != x2)
+ self.assertTrue(x1 == (x2 - x3))
+ self.assertTrue(x1 == x4)
+ self.assertTrue(x4 == x5)
+ self.assertTrue(x4 == x6)
+
+ self.assertTrue(x1 == 123456)
+ self.assertTrue(123456 == x1)
+ self.assertTrue(x1 == 123456L)
+ self.assertTrue(123456L == x1)
+ self.assertTrue(x1 == 123456.0)
+ self.assertTrue(123456.0 == x1)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+
+ def testCommodityEquality(self):
+ x0 = amount()
+ x1 = amount("$123.45")
+ x2 = amount("-$123.45")
+ x3 = amount("$-123.45")
+ x4 = amount("DM 123.45")
+ x5 = amount("-DM 123.45")
+ x6 = amount("DM -123.45")
+ x7 = amount("123.45 euro")
+ x8 = amount("-123.45 euro")
+ x9 = amount("123.45€")
+ x10 = amount("-123.45€")
+
+ self.assertTrue(x0.is_null())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.is_zero())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.is_realzero())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.sign() == 0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.compare(x1) < 0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.compare(x2) > 0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.compare(x0) == 0)
+
+ self.assertTrue(x1 != x2)
+ self.assertTrue(x1 != x4)
+ self.assertTrue(x1 != x7)
+ self.assertTrue(x1 != x9)
+ self.assertTrue(x2 == x3)
+ self.assertTrue(x4 != x5)
+ self.assertTrue(x5 == x6)
+ self.assertTrue(x7 == - x8)
+ self.assertTrue(x9 == - x10)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testComparisons(self):
+ x0 = amount()
+ x1 = amount(-123)
+ x2 = amount(123)
+ x3 = amount(-123.45)
+ x4 = amount(123.45)
+ x5 = amount("-123.45")
+ x6 = amount("123.45")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 > x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 < x2)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 > x3)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 < x4)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 > x5)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 < x6)
+
+ self.assertTrue(x1 > x3)
+ self.assertTrue(x3 <= x5)
+ self.assertTrue(x3 >= x5)
+ self.assertTrue(x3 < x1)
+ self.assertTrue(x3 < x4)
+
+ self.assertTrue(x1 < 100)
+ self.assertTrue(100 > x1)
+ self.assertTrue(x1 < 100L)
+ self.assertTrue(100L > x1)
+ self.assertTrue(x1 < 100.0)
+ self.assertTrue(100.0 > x1)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+
+ def testCommodityComparisons(self):
+ x1 = amount("$-123")
+ x2 = amount("$123.00")
+ x3 = amount(internalAmount("$-123.4544"))
+ x4 = amount(internalAmount("$123.4544"))
+ x5 = amount("$-123.45")
+ x6 = amount("$123.45")
+ x7 = amount("DM 123.45")
+
+ self.assertTrue(x1 > x3)
+ self.assertTrue(x3 <= x5)
+ self.assertTrue(x3 < x5)
+ self.assertTrue(x3 <= x5)
+ self.assertFalse(x3 == x5)
+ self.assertTrue(x3 < x1)
+ self.assertTrue(x3 < x4)
+ self.assertFalse(x6 == x7)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x6 < x7)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+
+ def testIntegerAddition(self):
+ x0 = amount()
+ x1 = amount(123)
+ y1 = amount(456)
+
+ self.assertEqual(amount(579), x1 + y1)
+ self.assertEqual(amount(579), x1 + 456)
+ self.assertEqual(amount(579), 456 + x1)
+
+ x1 += amount(456)
+ self.assertEqual(amount(579), x1)
+ x1 += 456
+ self.assertEqual(amount(1035), x1)
+
+ x4 = amount("123456789123456789123456789")
+
+ self.assertEqual(amount("246913578246913578246913578"), x4 + x4)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x4)
+
+ def testFractionalAddition(self):
+ x1 = amount(123.123)
+ y1 = amount(456.456)
+
+ self.assertEqual(amount(579.579), x1 + y1)
+ self.assertEqual(amount(579.579), x1 + 456.456)
+ self.assertEqual(amount(579.579), 456.456 + x1)
+
+ x1 += amount(456.456)
+ self.assertEqual(amount(579.579), x1)
+ x1 += 456.456
+ self.assertEqual(amount(1036.035), x1)
+ x1 += 456
+ self.assertEqual(amount(1492.035), x1)
+
+ x2 = amount("123456789123456789.123456789123456789")
+
+ self.assertEqual(amount("246913578246913578.246913578246913578"), x2 + x2)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x2)
+
+ def testCommodityAddition(self):
+ x0 = amount()
+ x1 = amount("$123.45")
+ x2 = amount(internalAmount("$123.456789"))
+ x3 = amount("DM 123.45")
+ x4 = amount("123.45 euro")
+ x5 = amount("123.45€")
+ x6 = amount("123.45")
+
+ self.assertEqual(amount("$246.90"), x1 + x1)
+ self.assertNotEqual(amount("$246.91"), x1 + x2)
+ self.assertEqual(internalAmount("$246.906789"), x1 + x2)
+
+ # Converting to string drops internal precision
+ self.assertEqual("$246.90", (x1 + x1).to_string())
+ self.assertEqual("$246.91", (x1 + x2).to_string())
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 + x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 + x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + x3)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + x4)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + x5)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + x6)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + 123.45)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 + 123)
+
+ self.assertEqual(amount("DM 246.90"), x3 + x3)
+ self.assertEqual(amount("246.90 euro"), x4 + x4)
+ self.assertEqual(amount("246.90€"), x5 + x5)
+
+ self.assertEqual("DM 246.90", (x3 + x3).to_string())
+ self.assertEqual("246.90 euro", (x4 + x4).to_string())
+ self.assertEqual("246.90€", (x5 + x5).to_string())
+
+ x1 += amount("$456.45")
+ self.assertEqual(amount("$579.90"), x1)
+ x1 += amount("$456.45")
+ self.assertEqual(amount("$1036.35"), x1)
+ x1 += amount("$456")
+ self.assertEqual(amount("$1492.35"), x1)
+
+ x7 = amount(internalAmount("$123456789123456789.123456789123456789"))
+
+ self.assertEqual(internalAmount("$246913578246913578.246913578246913578"), x7 + x7)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+
+ def testIntegerSubtraction(self):
+ x1 = amount(123)
+ y1 = amount(456)
+
+ self.assertEqual(amount(333), y1 - x1)
+ self.assertEqual(amount(-333), x1 - y1)
+ self.assertEqual(amount(23), x1 - 100)
+ self.assertEqual(amount(-23), 100 - x1)
+
+ x1 -= amount(456)
+ self.assertEqual(amount(-333), x1)
+ x1 -= 456
+ self.assertEqual(amount(-789), x1)
+
+ x4 = amount("123456789123456789123456789")
+ y4 = amount("8238725986235986")
+
+ self.assertEqual(amount("123456789115218063137220803"), x4 - y4)
+ self.assertEqual(amount("-123456789115218063137220803"), y4 - x4)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x4)
+ self.assertValid(y4)
+
+ def testFractionalSubtraction(self):
+ x1 = amount(123.123)
+ y1 = amount(456.456)
+
+ self.assertEqual(amount(-333.333), x1 - y1)
+ self.assertEqual(amount(333.333), y1 - x1)
+
+ x1 -= amount(456.456)
+ self.assertEqual(amount(-333.333), x1)
+ x1 -= 456.456
+ self.assertEqual(amount(-789.789), x1)
+ x1 -= 456
+ self.assertEqual(amount(-1245.789), x1)
+
+ x2 = amount("123456789123456789.123456789123456789")
+ y2 = amount("9872345982459.248974239578")
+
+ self.assertEqual(amount("123446916777474329.874482549545456789"), x2 - y2)
+ self.assertEqual(amount("-123446916777474329.874482549545456789"), y2 - x2)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x2)
+ self.assertValid(y2)
+
+ def testCommoditySubtraction(self):
+ x0 = amount()
+ x1 = amount("$123.45")
+ x2 = amount(internalAmount("$123.456789"))
+ x3 = amount("DM 123.45")
+ x4 = amount("123.45 euro")
+ x5 = amount("123.45€")
+ x6 = amount("123.45")
+
+ self.assertNotEqual(amount(), x1 - x1)
+ self.assertEqual(amount("$0"), x1 - x1)
+ self.assertEqual(amount("$23.45"), x1 - amount("$100.00"))
+ self.assertEqual(amount("$-23.45"), amount("$100.00") - x1)
+ self.assertNotEqual(amount("$-0.01"), x1 - x2)
+ self.assertEqual(internalAmount("$-0.006789"), x1 - x2)
+
+ # Converting to string drops internal precision. If an amount is
+ # zero, it drops the commodity as well.
+ self.assertEqual("$0.00", (x1 - x1).to_string())
+ self.assertEqual("$-0.01", (x1 - x2).to_string())
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 - x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 - x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - x3)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - x4)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - x5)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - x6)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - 123.45)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 - 123)
+
+ self.assertEqual(amount("DM 0.00"), x3 - x3)
+ self.assertEqual(amount("DM 23.45"), x3 - amount("DM 100.00"))
+ self.assertEqual(amount("DM -23.45"), amount("DM 100.00") - x3)
+ self.assertEqual(amount("0.00 euro"), x4 - x4)
+ self.assertEqual(amount("23.45 euro"), x4 - amount("100.00 euro"))
+ self.assertEqual(amount("-23.45 euro"), amount("100.00 euro") - x4)
+ self.assertEqual(amount("0.00€"), x5 - x5)
+ self.assertEqual(amount("23.45€"), x5 - amount("100.00€"))
+ self.assertEqual(amount("-23.45€"), amount("100.00€") - x5)
+
+ self.assertEqual("DM 0.00", (x3 - x3).to_string())
+ self.assertEqual("DM 23.45", (x3 - amount("DM 100.00")).to_string())
+ self.assertEqual("DM -23.45", (amount("DM 100.00") - x3).to_string())
+ self.assertEqual("0.00 euro", (x4 - x4).to_string())
+ self.assertEqual("23.45 euro", (x4 - amount("100.00 euro")).to_string())
+ self.assertEqual("-23.45 euro", (amount("100.00 euro") - x4).to_string())
+ self.assertEqual("0.00€", (x5 - x5).to_string())
+ self.assertEqual("23.45€", (x5 - amount("100.00€")).to_string())
+ self.assertEqual("-23.45€", (amount("100.00€") - x5).to_string())
+
+ x1 -= amount("$456.45")
+ self.assertEqual(amount("$-333.00"), x1)
+ x1 -= amount("$456.45")
+ self.assertEqual(amount("$-789.45"), x1)
+ x1 -= amount("$456")
+ self.assertEqual(amount("$-1245.45"), x1)
+
+ x7 = amount(internalAmount("$123456789123456789.123456789123456789"))
+ x8 = amount(internalAmount("$2354974984698.98459845984598"))
+
+ self.assertEqual(internalAmount("$123454434148472090.138858329277476789"), x7 - x8)
+ self.assertEqual("$123454434148472090.138858329277476789", (x7 - x8).to_string())
+ self.assertEqual("$123454434148472090.14",
+ (amount("$1.00") * (x7 - x8)).to_string())
+ self.assertEqual(internalAmount("$-123454434148472090.138858329277476789"), x8 - x7)
+ self.assertEqual("$-123454434148472090.138858329277476789", (x8 - x7).to_string())
+ self.assertEqual("$-123454434148472090.14",
+ (amount("$1.00") * (x8 - x7)).to_string())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+
+ def testIntegerMultiplication(self):
+ x1 = amount(123)
+ y1 = amount(456)
+
+ self.assertEqual(amount(0), x1 * 0)
+ self.assertEqual(amount(0), amount(0) * x1)
+ self.assertEqual(amount(0), 0 * x1)
+ self.assertEqual(x1, x1 * 1)
+ self.assertEqual(x1, amount(1) * x1)
+ self.assertEqual(x1, 1 * x1)
+ self.assertEqual(- x1, x1 * -1)
+ self.assertEqual(- x1, amount(-1) * x1)
+ self.assertEqual(- x1, -1 * x1)
+ self.assertEqual(amount(56088), x1 * y1)
+ self.assertEqual(amount(56088), y1 * x1)
+ self.assertEqual(amount(56088), x1 * 456)
+ self.assertEqual(amount(56088), amount(456) * x1)
+ self.assertEqual(amount(56088), 456 * x1)
+
+ x1 *= amount(123)
+ self.assertEqual(amount(15129), x1)
+ x1 *= 123
+ self.assertEqual(amount(1860867), x1)
+
+ x4 = amount("123456789123456789123456789")
+
+ self.assertEqual(amount("15241578780673678546105778281054720515622620750190521"),
+ x4 * x4)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x4)
+
+ def testFractionalMultiplication(self):
+ x1 = amount(123.123)
+ y1 = amount(456.456)
+
+ self.assertEqual(amount(0), x1 * 0)
+ self.assertEqual(amount(0), amount(0) * x1)
+ self.assertEqual(amount(0), 0 * x1)
+ self.assertEqual(x1, x1 * 1)
+ self.assertEqual(x1, amount(1) * x1)
+ self.assertEqual(x1, 1 * x1)
+ self.assertEqual(- x1, x1 * -1)
+ self.assertEqual(- x1, amount(-1) * x1)
+ self.assertEqual(- x1, -1 * x1)
+ self.assertEqual(amount("56200.232088"), x1 * y1)
+ self.assertEqual(amount("56200.232088"), y1 * x1)
+ self.assertEqual(amount("56200.232088"), x1 * 456.456)
+ self.assertEqual(amount("56200.232088"), amount(456.456) * x1)
+ self.assertEqual(amount("56200.232088"), 456.456 * x1)
+
+ x1 *= amount(123.123)
+ self.assertEqual(amount("15159.273129"), x1)
+ x1 *= 123.123
+ self.assertEqual(amount("1866455.185461867"), x1)
+ x1 *= 123
+ self.assertEqual(amount("229573987.811809641"), x1)
+
+ x2 = amount("123456789123456789.123456789123456789")
+
+ self.assertEqual(amount("15241578780673678546105778311537878.046486820281054720515622620750190521"),
+ x2 * x2)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x2)
+
+ def testCommodityMultiplication(self):
+ x0 = amount()
+ x1 = amount("$123.12")
+ y1 = amount("$456.45")
+ x2 = amount(internalAmount("$123.456789"))
+ x3 = amount("DM 123.45")
+ x4 = amount("123.45 euro")
+ x5 = amount("123.45€")
+
+ self.assertEqual(amount("$0.00"), x1 * 0)
+ self.assertEqual(amount("$0.00"), 0 * x1)
+ self.assertEqual(x1, x1 * 1)
+ self.assertEqual(x1, 1 * x1)
+ self.assertEqual(- x1, x1 * -1)
+ self.assertEqual(- x1, -1 * x1)
+ self.assertEqual(internalAmount("$56198.124"), x1 * y1)
+ self.assertEqual("$56198.12", (x1 * y1).to_string())
+ self.assertEqual(internalAmount("$56198.124"), y1 * x1)
+ self.assertEqual("$56198.12", (y1 * x1).to_string())
+
+ # Internal amounts retain their precision, even when being
+ # converted to strings
+ self.assertEqual(internalAmount("$15199.99986168"), x1 * x2)
+ self.assertEqual(internalAmount("$15199.99986168"), x2 * x1)
+ self.assertEqual("$15200.00", (x1 * x2).to_string())
+ self.assertEqual("$15199.99986168", (x2 * x1).to_string())
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 * x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 * x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 * x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 * x3)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 * x4)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 * x5)
+
+ x1 *= amount("123.12")
+ self.assertEqual(internalAmount("$15158.5344"), x1)
+ self.assertEqual("$15158.53", x1.to_string())
+ x1 *= 123.12
+ self.assertEqual(internalAmount("$1866318.755328"), x1)
+ self.assertEqual("$1866318.76", x1.to_string())
+ x1 *= 123
+ self.assertEqual(internalAmount("$229557206.905344"), x1)
+ self.assertEqual("$229557206.91", x1.to_string())
+
+ x7 = amount(internalAmount("$123456789123456789.123456789123456789"))
+
+ self.assertEqual(internalAmount("$15241578780673678546105778311537878.046486820281054720515622620750190521"),
+ x7 * x7)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x7)
+
+ def testIntegerDivision(self):
+ x1 = amount(123)
+ y1 = amount(456)
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / 0)
+ self.assertEqual(amount(0), amount(0) / x1)
+ self.assertEqual(amount(0), 0 / x1)
+ self.assertEqual(x1, x1 / 1)
+ self.assertEqual(amount("0.008130"), amount(1) / x1)
+ self.assertEqual(amount("0.008130"), 1 / x1)
+ self.assertEqual(- x1, x1 / -1)
+ self.assertEqual(- amount("0.008130"), amount(-1) / x1)
+ self.assertEqual(- amount("0.008130"), -1 / x1)
+ self.assertEqual(amount("0.269737"), x1 / y1)
+ self.assertEqual(amount("3.707317"), y1 / x1)
+ self.assertEqual(amount("0.269737"), x1 / 456)
+ self.assertEqual(amount("3.707317"), amount(456) / x1)
+ self.assertEqual(amount("3.707317"), 456 / x1)
+
+ x1 /= amount(456)
+ self.assertEqual(amount("0.269737"), x1)
+ x1 /= 456
+ self.assertEqual(amount("0.00059152850877193"), x1)
+
+ x4 = amount("123456789123456789123456789")
+ y4 = amount("56")
+
+ self.assertEqual(amount(1), x4 / x4)
+ self.assertEqual(amount("2204585520061728377204585.517857"), x4 / y4)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x4)
+ self.assertValid(y4)
+
+ def testFractionalDivision(self):
+ x1 = amount(123.123)
+ y1 = amount(456.456)
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / 0)
+ self.assertEqual(amount("0.008121959"), amount(1.0) / x1)
+ self.assertEqual(amount("0.008121959"), 1.0 / x1)
+ self.assertEqual(x1, x1 / 1.0)
+ self.assertEqual(amount("0.008121959"), amount(1.0) / x1)
+ self.assertEqual(amount("0.008121959"), 1.0 / x1)
+ self.assertEqual(- x1, x1 / -1.0)
+ self.assertEqual(- amount("0.008121959"), amount(-1.0) / x1)
+ self.assertEqual(- amount("0.008121959"), -1.0 / x1)
+ self.assertEqual(amount("0.269736842105263"), x1 / y1)
+ self.assertEqual(amount("3.707317073170732"), y1 / x1)
+ self.assertEqual(amount("0.269736842105263"), x1 / 456.456)
+ self.assertEqual(amount("3.707317073170732"), amount(456.456) / x1)
+ self.assertEqual(amount("3.707317073170732"), 456.456 / x1)
+
+ x1 /= amount(456.456)
+ self.assertEqual(amount("0.269736842105263"), x1)
+ x1 /= 456.456
+ self.assertEqual(amount("0.000590937225286255411255411255411255411"), x1)
+ x1 /= 456
+ self.assertEqual(amount("0.000001295914967733016252753094858358016252192982456140350877192982456140350877192982"), x1)
+
+ x4 = amount("1234567891234567.89123456789")
+ y4 = amount("56.789")
+
+ self.assertEqual(amount(1.0), x4 / x4)
+ self.assertEqual(amount("21739560323910.7554497273748437197344556164046"), x4 / y4)
+
+ self.assertValid(x1)
+ self.assertValid(y1)
+ self.assertValid(x4)
+ self.assertValid(y4)
+
+ def testCommodityDivision(self):
+ x0 = amount()
+ x1 = amount("$123.12")
+ y1 = amount("$456.45")
+ x2 = amount(internalAmount("$123.456789"))
+ x3 = amount("DM 123.45")
+ x4 = amount("123.45 euro")
+ x5 = amount("123.45€")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / 0)
+ self.assertEqual(amount("$0.00"), 0 / x1)
+ self.assertEqual(x1, x1 / 1)
+ self.assertEqual(internalAmount("$0.00812216"), 1 / x1)
+ self.assertEqual(- x1, x1 / -1)
+ self.assertEqual(internalAmount("$-0.00812216"), -1 / x1)
+ self.assertEqual(internalAmount("$0.26973382"), x1 / y1)
+ self.assertEqual("$0.27", (x1 / y1).to_string())
+ self.assertEqual(internalAmount("$3.70735867"), y1 / x1)
+ self.assertEqual("$3.71", (y1 / x1).to_string())
+
+ # Internal amounts retain their precision, even when being
+ # converted to strings
+ self.assertEqual(internalAmount("$0.99727201"), x1 / x2)
+ self.assertEqual(internalAmount("$1.00273545321637426901"), x2 / x1)
+ self.assertEqual("$1.00", (x1 / x2).to_string())
+ self.assertEqual("$1.00273545321637426901", (x2 / x1).to_string())
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 / x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0 / x0)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / x3)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / x4)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1 / x5)
+
+ x1 /= amount("123.12")
+ self.assertEqual(internalAmount("$1.00"), x1)
+ self.assertEqual("$1.00", x1.to_string())
+ x1 /= 123.12
+ self.assertEqual(internalAmount("$0.00812216"), x1)
+ self.assertEqual("$0.01", x1.to_string())
+ x1 /= 123
+ self.assertEqual(internalAmount("$0.00006603"), x1)
+ self.assertEqual("$0.00", x1.to_string())
+
+ x6 = amount(internalAmount("$237235987235987.98723987235978"))
+ x7 = amount(internalAmount("$123456789123456789.123456789123456789"))
+
+ self.assertEqual(amount("$1"), x7 / x7)
+ self.assertEqual(internalAmount("$0.0019216115121765559608381226612019501046413574469262"),
+ x6 / x7)
+ self.assertEqual(internalAmount("$520.39654928343335571379527154924040947271699678158689736256"),
+ x7 / x6)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+
+ def testNegation(self):
+ x0 = amount()
+ x1 = amount(-123456)
+ x3 = amount(-123.456)
+ x5 = amount("-123456")
+ x6 = amount("-123.456")
+ x7 = amount("-123456")
+ x8 = amount("-123.456")
+ x9 = amount(- x3)
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.negate())
+ self.assertEqual(x5, x1)
+ self.assertEqual(x7, x1)
+ self.assertEqual(x6, x3)
+ self.assertEqual(x8, x3)
+ self.assertEqual(- x6, x9)
+ self.assertEqual(x3.negate(), x9)
+
+ x10 = amount(x9.negate())
+
+ self.assertEqual(x3, x10)
+
+ self.assertValid(x1)
+ self.assertValid(x3)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testCommodityNegation(self):
+ x1 = amount("$123.45")
+ x2 = amount("-$123.45")
+ x3 = amount("$-123.45")
+ x4 = amount("DM 123.45")
+ x5 = amount("-DM 123.45")
+ x6 = amount("DM -123.45")
+ x7 = amount("123.45 euro")
+ x8 = amount("-123.45 euro")
+ x9 = amount("123.45€")
+ x10 = amount("-123.45€")
+
+ self.assertEqual(amount("$-123.45"), - x1)
+ self.assertEqual(amount("$123.45"), - x2)
+ self.assertEqual(amount("$123.45"), - x3)
+ self.assertEqual(amount("DM -123.45"), - x4)
+ self.assertEqual(amount("DM 123.45"), - x5)
+ self.assertEqual(amount("DM 123.45"), - x6)
+ self.assertEqual(amount("-123.45 euro"), - x7)
+ self.assertEqual(amount("123.45 euro"), - x8)
+ self.assertEqual(amount("-123.45€"), - x9)
+ self.assertEqual(amount("123.45€"), - x10)
+
+ self.assertEqual(amount("$-123.45"), x1.negate())
+ self.assertEqual(amount("$123.45"), x2.negate())
+ self.assertEqual(amount("$123.45"), x3.negate())
+
+ self.assertEqual("$-123.45", (- x1).to_string())
+ self.assertEqual("$123.45", (- x2).to_string())
+ self.assertEqual("$123.45", (- x3).to_string())
+ self.assertEqual("DM -123.45", (- x4).to_string())
+ self.assertEqual("DM 123.45", (- x5).to_string())
+ self.assertEqual("DM 123.45", (- x6).to_string())
+ self.assertEqual("-123.45 euro", (- x7).to_string())
+ self.assertEqual("123.45 euro", (- x8).to_string())
+ self.assertEqual("-123.45€", (- x9).to_string())
+ self.assertEqual("123.45€", (- x10).to_string())
+
+ self.assertEqual(amount("$-123.45"), x1.negate())
+ self.assertEqual(amount("$123.45"), x2.negate())
+ self.assertEqual(amount("$123.45"), x3.negate())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+ self.assertValid(x6)
+ self.assertValid(x7)
+ self.assertValid(x8)
+ self.assertValid(x9)
+ self.assertValid(x10)
+
+ def testAbs(self):
+ x0 = amount()
+ x1 = amount(-1234)
+ x2 = amount(1234)
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.abs())
+ self.assertEqual(amount(1234), x1.abs())
+ self.assertEqual(amount(1234), x2.abs())
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+
+ def testCommodityAbs(self):
+ x1 = amount("$-1234.56")
+ x2 = amount("$1234.56")
+
+ self.assertEqual(amount("$1234.56"), x1.abs())
+ self.assertEqual(amount("$1234.56"), x2.abs())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+
+ def testFractionalRound(self):
+ x0 = amount()
+ x1 = amount("1234.567890")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.precision)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.round())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.round(2))
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.unround())
+ self.assertEqual(6, x1.precision)
+
+ x1b = amount(x1.unround())
+
+ self.assertEqual(x1b.precision, x1b.unround().precision)
+
+ y7 = amount(x1.round(7))
+ y6 = amount(x1.round(6))
+ y5 = amount(x1.round(5))
+ y4 = amount(x1.round(4))
+ y3 = amount(x1.round(3))
+ y2 = amount(x1.round(2))
+ y1 = amount(x1.round(1))
+ y0 = amount(x1.round(0))
+
+ self.assertEqual(6, y7.precision)
+ self.assertEqual(6, y6.precision)
+ self.assertEqual(5, y5.precision)
+ self.assertEqual(4, y4.precision)
+ self.assertEqual(3, y3.precision)
+ self.assertEqual(2, y2.precision)
+ self.assertEqual(1, y1.precision)
+ self.assertEqual(0, y0.precision)
+
+ self.assertEqual(amount("1234.56789"), y7)
+ self.assertEqual(amount("1234.56789"), y6)
+ self.assertEqual(amount("1234.56789"), y5)
+ self.assertEqual(amount("1234.5679"), y4)
+ self.assertEqual(amount("1234.568"), y3)
+ self.assertEqual(amount("1234.57"), y2)
+ self.assertEqual(amount("1234.6"), y1)
+ self.assertEqual(amount("1235"), y0)
+
+ x2 = amount("9876.543210")
+
+ self.assertEqual(amount("9876.543210"), x2.round(6))
+ self.assertEqual(amount("9876.54321"), x2.round(5))
+ self.assertEqual(amount("9876.5432"), x2.round(4))
+ self.assertEqual(amount("9876.543"), x2.round(3))
+ self.assertEqual(amount("9876.54"), x2.round(2))
+ self.assertEqual(amount("9876.5"), x2.round(1))
+ self.assertEqual(amount("9877"), x2.round(0))
+
+ x3 = amount("-1234.567890")
+
+ self.assertEqual(amount("-1234.56789"), x3.round(6))
+ self.assertEqual(amount("-1234.56789"), x3.round(5))
+ self.assertEqual(amount("-1234.5679"), x3.round(4))
+ self.assertEqual(amount("-1234.568"), x3.round(3))
+ self.assertEqual(amount("-1234.57"), x3.round(2))
+ self.assertEqual(amount("-1234.6"), x3.round(1))
+ self.assertEqual(amount("-1235"), x3.round(0))
+
+ x4 = amount("-9876.543210")
+
+ self.assertEqual(amount("-9876.543210"), x4.round(6))
+ self.assertEqual(amount("-9876.54321"), x4.round(5))
+ self.assertEqual(amount("-9876.5432"), x4.round(4))
+ self.assertEqual(amount("-9876.543"), x4.round(3))
+ self.assertEqual(amount("-9876.54"), x4.round(2))
+ self.assertEqual(amount("-9876.5"), x4.round(1))
+ self.assertEqual(amount("-9877"), x4.round(0))
+
+ x5 = amount("0.0000000000000000000000000000000000001")
+
+ self.assertEqual(amount("0.0000000000000000000000000000000000001"),
+ x5.round(37))
+ self.assertEqual(amount(0), x5.round(36))
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+
+ def testCommodityRound(self):
+ x1 = amount(internalAmount("$1234.567890"))
+
+ self.assertEqual(internalAmount("$1234.56789"), x1.round(6))
+ self.assertEqual(internalAmount("$1234.56789"), x1.round(5))
+ self.assertEqual(internalAmount("$1234.5679"), x1.round(4))
+ self.assertEqual(internalAmount("$1234.568"), x1.round(3))
+ self.assertEqual(amount("$1234.57"), x1.round(2))
+ self.assertEqual(amount("$1234.6"), x1.round(1))
+ self.assertEqual(amount("$1235"), x1.round(0))
+
+ x2 = amount(internalAmount("$9876.543210"))
+
+ self.assertEqual(internalAmount("$9876.543210"), x2.round(6))
+ self.assertEqual(internalAmount("$9876.54321"), x2.round(5))
+ self.assertEqual(internalAmount("$9876.5432"), x2.round(4))
+ self.assertEqual(internalAmount("$9876.543"), x2.round(3))
+ self.assertEqual(amount("$9876.54"), x2.round(2))
+ self.assertEqual(amount("$9876.5"), x2.round(1))
+ self.assertEqual(amount("$9877"), x2.round(0))
+
+ x3 = amount(internalAmount("$-1234.567890"))
+
+ self.assertEqual(internalAmount("$-1234.56789"), x3.round(6))
+ self.assertEqual(internalAmount("$-1234.56789"), x3.round(5))
+ self.assertEqual(internalAmount("$-1234.5679"), x3.round(4))
+ self.assertEqual(internalAmount("$-1234.568"), x3.round(3))
+ self.assertEqual(amount("$-1234.57"), x3.round(2))
+ self.assertEqual(amount("$-1234.6"), x3.round(1))
+ self.assertEqual(amount("$-1235"), x3.round(0))
+
+ x4 = amount(internalAmount("$-9876.543210"))
+
+ self.assertEqual(internalAmount("$-9876.543210"), x4.round(6))
+ self.assertEqual(internalAmount("$-9876.54321"), x4.round(5))
+ self.assertEqual(internalAmount("$-9876.5432"), x4.round(4))
+ self.assertEqual(internalAmount("$-9876.543"), x4.round(3))
+ self.assertEqual(amount("$-9876.54"), x4.round(2))
+ self.assertEqual(amount("$-9876.5"), x4.round(1))
+ self.assertEqual(amount("$-9877"), x4.round(0))
+
+ x5 = amount("$123.45")
+
+ x5 *= 100.12
+
+ self.assertEqual(internalAmount("$12359.814"), x5)
+ self.assertEqual("$12359.81", x5.to_string())
+ self.assertEqual("$12359.814", x5.to_fullstring())
+ self.assertEqual("$12359.814", x5.unround().to_string())
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+ self.assertValid(x5)
+
+ def testCommodityDisplayRound(self):
+ x1 = amount("$0.85")
+ x2 = amount("$0.1")
+
+ x1 *= 0.19
+
+ self.assertNotEqual(amount("$0.16"), x1)
+ self.assertEqual(internalAmount("$0.1615"), x1)
+ self.assertEqual("$0.16", x1.to_string())
+
+ self.assertEqual(amount("$0.10"), x2)
+ self.assertNotEqual(internalAmount("$0.101"), x2)
+ self.assertEqual("$0.10", x2.to_string())
+
+ x1 *= 7
+
+ self.assertNotEqual(amount("$1.13"), x1)
+ self.assertEqual(internalAmount("$1.1305"), x1)
+ self.assertEqual("$1.13", x1.to_string())
+
+ def testReduction(self):
+ x0 = amount()
+ x1 = amount("60s")
+ x2 = amount("600s")
+ x3 = amount("6000s")
+ x4 = amount("360000s")
+ x5 = amount("10m")
+ x6 = amount("100m")
+ x7 = amount("1000m")
+ x8 = amount("10000m")
+ x9 = amount("10h")
+ x10 = amount("100h")
+ x11 = amount("1000h")
+ x12 = amount("10000h")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.reduce())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.unreduce())
+ self.assertEqual(x2, x5)
+ self.assertEqual(x3, x6)
+ self.assertEqual(x4, x10)
+ self.assertEqual("100.0h", x4.unreduce().to_string())
+
+ def testSign(self):
+ x0 = amount()
+ x1 = amount("0.0000000000000000000000000000000000001")
+ x2 = amount("-0.0000000000000000000000000000000000001")
+ x3 = amount("1")
+ x4 = amount("-1")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.sign())
+ self.assertTrue(x1.sign() > 0)
+ self.assertTrue(x2.sign() < 0)
+ self.assertTrue(x3.sign() > 0)
+ self.assertTrue(x4.sign() < 0)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+
+ def testCommoditySign(self):
+ x1 = amount(internalAmount("$0.0000000000000000000000000000000000001"))
+ x2 = amount(internalAmount("$-0.0000000000000000000000000000000000001"))
+ x3 = amount("$1")
+ x4 = amount("$-1")
+
+ self.assertTrue(x1.sign() != 0)
+ self.assertTrue(x2.sign() != 0)
+ self.assertTrue(x3.sign() > 0)
+ self.assertTrue(x4.sign() < 0)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+ self.assertValid(x3)
+ self.assertValid(x4)
+
+ def testTruth(self):
+ x0 = amount()
+ x1 = amount("1234")
+ x2 = amount("1234.56")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: 1 if x0 else 0)
+
+ self.assertTrue(x1)
+ self.assertTrue(x2)
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+ self.assertValid(x2)
+
+ def testCommodityTruth(self):
+ x1 = amount("$1234")
+ x2 = amount("$1234.56")
+
+ if x1:
+ self.assertTrue(True)
+ else:
+ self.assertTrue(False)
+
+ if x2:
+ self.assertTrue(True)
+ else:
+ self.assertTrue(False)
+
+ self.assertValid(x1)
+ self.assertValid(x2)
+
+ def testForZero(self):
+ x0 = amount()
+ x1 = amount("0.000000000000000000001")
+
+ self.assertTrue(x1)
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.is_zero())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.is_realzero())
+ self.assertFalse(x1.is_zero())
+ self.assertFalse(x1.is_realzero())
+
+ self.assertValid(x0)
+ self.assertValid(x1)
+
+ def testCommodityForZero(self):
+ x1 = amount(internalAmount("$0.000000000000000000001"))
+
+ self.assertFalse(x1)
+ self.assertTrue(x1.is_zero())
+ self.assertFalse(x1.is_realzero())
+
+ self.assertValid(x1)
+
+ def testIntegerConversion(self):
+ x0 = amount()
+ x1 = amount(123456)
+ x2 = amount("12345682348723487324")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.to_long())
+ self.assertRaises(exceptions.ArithmeticError, lambda: x0.to_double())
+ self.assertFalse(x2.fits_in_long())
+ self.assertEqual(123456, x1.to_long())
+ self.assertEqual(123456.0, x1.to_double())
+ self.assertEqual("123456", x1.to_string())
+ self.assertEqual("123456", x1.quantity_string)
+
+ self.assertValid(x1)
+
+ def testFractionalConversion(self):
+ x1 = amount(1234.56)
+ x2 = amount("1234.5683787634678348734")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1.to_long()) # loses precision
+ self.assertRaises(exceptions.ArithmeticError, lambda: x2.to_double()) # loses precision
+ self.assertFalse(x2.fits_in_double())
+ self.assertEqual(1234, x1.to_long(True))
+ self.assertEqual(1234.56, x1.to_double())
+ self.assertEqual("1234.56", x1.to_string())
+ self.assertEqual("1234.56", x1.quantity_string)
+
+ self.assertValid(x1)
+
+ def testCommodityConversion(self):
+ x1 = amount("$1234.56")
+
+ self.assertRaises(exceptions.ArithmeticError, lambda: x1.to_long()) # loses precision
+ self.assertEqual(1234, x1.to_long(True))
+ self.assertEqual(1234.56, x1.to_double())
+ self.assertEqual("$1234.56", x1.to_string())
+ self.assertEqual("1234.56", x1.quantity_string)
+
+ self.assertValid(x1)
+
+ def testPrinting(self):
+ pass
+ #x0 = amount()
+ #x1 = amount("982340823.380238098235098235098235098")
+ #
+ #bufstr = StringIO()
+ #self.assertRaises(exceptions.ArithmeticError, lambda: bufstr.write(x0))
+ #
+ #bufstr = StringIO()
+ #bufstr.write(x1)
+ #
+ #self.assertEqual("982340823.380238098235098235098235098",
+ # bufstr.getvalue())
+ #
+ #self.assertValid(x0)
+ #self.assertValid(x1)
+
+ def testCommodityPrinting(self):
+ pass
+ #x1 = amount(internalAmount("$982340823.386238098235098235098235098"))
+ #x2 = amount("$982340823.38")
+ #
+ #bufstr = StringIO()
+ #bufstr.write(x1)
+ #
+ #self.assertEqual("$982340823.386238098235098235098235098",
+ # bufstr.getvalue())
+ #
+ #bufstr = StringIO()
+ #bufstr.write((x1 * x2).to_string())
+ #
+ #self.assertEqual("$964993493285024293.18099172508158508135413499124",
+ # bufstr.getvalue())
+ #
+ #bufstr = StringIO()
+ #bufstr.write((x2 * x1).to_string())
+ #
+ #self.assertEqual("$964993493285024293.18", bufstr.getvalue())
+ #
+ #self.assertValid(x1)
+ #self.assertValid(x2)
+
+ def testSerialization(self):
+ pass
+ #x0 = amount()
+ #x1 = amount("$8,192.34")
+ #x2 = amount("8192.34")
+ #x3 = amount("8192.34")
+ #x4 = amount("-8192.34")
+ #x5 = amount(x4)
+ #
+ ## Force x3's pointer to actually be set to null_commodity
+ ##x3.set_commodity(*x3.current_pool.null_commodity)
+ #
+ #buf = ""
+ #storage = StringIO()
+ #self.assertRaises(exceptions.ArithmeticError, lambda: x0.write(storage))
+ #x1.write(storage)
+ #x2.write(storage)
+ #x3.write(storage)
+ #x4.write(storage)
+ #x5.write(storage)
+ #buf = storage.getvalue()
+ #
+ #x1b = amount()
+ #x2b = amount()
+ #x3b = amount()
+ #x4b = amount()
+ #x5b = amount()
+ #
+ #storage = StringIO(buf)
+ #x1b.read(storage)
+ #x2b.read(storage)
+ #x3b.read(storage)
+ #x4b.read(storage)
+ #x5b.read(storage)
+ #
+ #self.assertEqual(x1, x1b)
+ #self.assertEqual(x2, x2b)
+ #self.assertEqual(x3, x3b)
+ #self.assertEqual(x4, x4b)
+ #
+ #ptr = buf.c_str()
+ #
+ #x1c = amount()
+ #x2c = amount()
+ #x3c = amount()
+ #x4c = amount()
+ #x5c = amount()
+ #
+ #x1c.read(ptr)
+ #x2c.read(ptr)
+ #x3c.read(ptr)
+ #x4c.read(ptr)
+ #x5c.read(ptr)
+ #
+ #self.assertEqual(x1, x1b)
+ #self.assertEqual(x2, x2b)
+ #self.assertEqual(x3, x3b)
+ #self.assertEqual(x4, x4b)
+ #
+ #self.assertValid(x1)
+ #self.assertValid(x2)
+ #self.assertValid(x3)
+ #self.assertValid(x4)
+ #self.assertValid(x1b)
+ #self.assertValid(x2b)
+ #self.assertValid(x3b)
+ #self.assertValid(x4b)
+ #self.assertValid(x1c)
+ #self.assertValid(x2c)
+ #self.assertValid(x3c)
+ #self.assertValid(x4c)
+
+
+def suite():
+ return unittest.TestLoader().loadTestsFromTestCase(t_amountTestCase)
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python/tuples.h b/python/tuples.h
new file mode 100644
index 00000000..d7695934
--- /dev/null
+++ b/python/tuples.h
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2003-2008, John Wiegley. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of New Artisans LLC nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// Copyright 2004-2007 Roman Yakovenko.
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef TUPLES_HPP_16_JAN_2007
+#define TUPLES_HPP_16_JAN_2007
+
+#include "boost/python.hpp"
+#include "boost/tuple/tuple.hpp"
+#include "boost/python/object.hpp" //len function
+#include <boost/mpl/int.hpp>
+#include <boost/mpl/next.hpp>
+
+/**
+ * Converts boost::tuples::tuple<...> to\from Python tuple
+ *
+ * The conversion is done "on-the-fly", you should only register the conversion
+ * with your tuple classes.
+ * For example:
+ *
+ * typedef boost::tuples::tuple< int, double, std::string > triplet;
+ * boost::python::register_tuple< triplet >();
+ *
+ * That's all. After this point conversion to\from next types will be handled
+ * by Boost.Python library:
+ *
+ * triplet
+ * triplet& ( return type only )
+ * const triplet
+ * const triplet&
+ *
+ * Implementation description.
+ * The conversion uses Boost.Python custom r-value converters. r-value converters
+ * is very powerful and undocumented feature of the library. The only documentation
+ * we have is http://boost.org/libs/python/doc/v2/faq.html#custom_string .
+ *
+ * The conversion consists from two parts: "to" and "from".
+ *
+ * "To" conversion
+ * The "to" part is pretty easy and well documented ( http://docs.python.org/api/api.html ).
+ * You should use Python C API to create an instance of a class and than you
+ * initialize the relevant members of the instance.
+ *
+ * "From" conversion
+ * Lets start from analyzing one of the use case Boost.Python library have to
+ * deal with:
+ *
+ * void do_smth( const triplet& arg ){...}
+ *
+ * In order to allow calling this function from Python, the library should keep
+ * parameter "arg" alive until the function returns. In other words, the library
+ * should provide instances life-time management. The provided interface is not
+ * ideal and could be improved. You have to implement two functions:
+ *
+ * void* convertible( PyObject* obj )
+ * Checks whether the "obj" could be converted to an instance of the desired
+ * class. If true, the function should return "obj", otherwise NULL
+ *
+ * void construct( PyObject* obj, converter::rvalue_from_python_stage1_data* data)
+ * Constructs the instance of the desired class. This function will be called
+ * if and only if "convertible" function returned true. The first argument
+ * is Python object, which was passed as parameter to "convertible" function.
+ * The second object is some kind of memory allocator for one object. Basically
+ * it keeps a memory chunk. You will use the memory for object allocation.
+ *
+ * For some unclear for me reason, the library implements "C style Inheritance"
+ * ( http://www.embedded.com/97/fe29712.htm ). So, in order to create new
+ * object in the storage you have to cast to the "right" class:
+ *
+ * typedef converter::rvalue_from_python_storage<your_type_t> storage_t;
+ * storage_t* the_storage = reinterpret_cast<storage_t*>( data );
+ * void* memory_chunk = the_storage->storage.bytes;
+ *
+ * "memory_chunk" points to the memory, where the instance will be allocated.
+ *
+ * In order to create object at specific location, you should use placement new
+ * operator:
+ *
+ * your_type_t* instance = new (memory_chunk) your_type_t();
+ *
+ * Now, you can continue to initialize the instance.
+ *
+ * instance->set_xyz = read xyz from obj
+ *
+ * If "your_type_t" constructor requires some arguments, "read" the Python
+ * object before you call the constructor:
+ *
+ * xyz_type xyz = read xyz from obj
+ * your_type_t* instance = new (memory_chunk) your_type_t(xyz);
+ *
+ * Hint:
+ * In most case you don't really need\have to work with C Python API. Let
+ * Boost.Python library to do some work for you!
+ *
+ **/
+
+namespace boost{ namespace python{
+
+namespace details{
+
+//Small helper function, introduced to allow short syntax for index incrementing
+template< int index>
+typename mpl::next< mpl::int_< index > >::type increment_index(){
+ typedef typename mpl::next< mpl::int_< index > >::type next_index_type;
+ return next_index_type();
+}
+
+}
+
+template< class TTuple >
+struct to_py_tuple{
+
+ typedef mpl::int_< tuples::length< TTuple >::value > length_type;
+
+ static PyObject* convert(const TTuple& c_tuple){
+ list values;
+ //add all c_tuple items to "values" list
+ convert_impl( c_tuple, values, mpl::int_< 0 >(), length_type() );
+ //create Python tuple from the list
+ return incref( python::tuple( values ).ptr() );
+ }
+
+private:
+
+ template< int index, int length >
+ static void
+ convert_impl( const TTuple &c_tuple, list& values, mpl::int_< index >, mpl::int_< length > ) {
+ values.append( c_tuple.template get< index >() );
+ convert_impl( c_tuple, values, details::increment_index<index>(), length_type() );
+ }
+
+ template< int length >
+ static void
+ convert_impl( const TTuple&, list& values, mpl::int_< length >, mpl::int_< length >)
+ {}
+
+};
+
+
+template< class TTuple>
+struct from_py_sequence{
+
+ typedef TTuple tuple_type;
+
+ typedef mpl::int_< tuples::length< TTuple >::value > length_type;
+
+ static void*
+ convertible(PyObject* py_obj){
+
+ if( !PySequence_Check( py_obj ) ){
+ return 0;
+ }
+
+ if( !PyObject_HasAttrString( py_obj, "__len__" ) ){
+ return 0;
+ }
+
+ python::object py_sequence( handle<>( borrowed( py_obj ) ) );
+
+ if( tuples::length< TTuple >::value != len( py_sequence ) ){
+ return 0;
+ }
+
+ if( convertible_impl( py_sequence, mpl::int_< 0 >(), length_type() ) ){
+ return py_obj;
+ }
+ else{
+ return 0;
+ }
+ }
+
+ static void
+ construct( PyObject* py_obj, converter::rvalue_from_python_stage1_data* data){
+ typedef converter::rvalue_from_python_storage<TTuple> storage_t;
+ storage_t* the_storage = reinterpret_cast<storage_t*>( data );
+ void* memory_chunk = the_storage->storage.bytes;
+ TTuple* c_tuple = new (memory_chunk) TTuple();
+ data->convertible = memory_chunk;
+
+ python::object py_sequence( handle<>( borrowed( py_obj ) ) );
+ construct_impl( py_sequence, *c_tuple, mpl::int_< 0 >(), length_type() );
+ }
+
+ static TTuple to_c_tuple( PyObject* py_obj ){
+ if( !convertible( py_obj ) ){
+ throw std::runtime_error( "Unable to construct boost::tuples::tuple from Python object!" );
+ }
+ TTuple c_tuple;
+ python::object py_sequence( handle<>( borrowed( py_obj ) ) );
+ construct_impl( py_sequence, c_tuple, mpl::int_< 0 >(), length_type() );
+ return c_tuple;
+ }
+
+private:
+
+ template< int index, int length >
+ static bool
+ convertible_impl( const python::object& py_sequence, mpl::int_< index >, mpl::int_< length > ){
+
+ typedef typename tuples::element< index, TTuple>::type element_type;
+
+ object element = py_sequence[index];
+ extract<element_type> type_checker( element );
+ if( !type_checker.check() ){
+ return false;
+ }
+ else{
+ return convertible_impl( py_sequence, details::increment_index<index>(), length_type() );
+ }
+ }
+
+ template< int length >
+ static bool
+ convertible_impl( const python::object& py_sequence, mpl::int_< length >, mpl::int_< length > ){
+ return true;
+ }
+
+ template< int index, int length >
+ static void
+ construct_impl( const python::object& py_sequence, TTuple& c_tuple, mpl::int_< index >, mpl::int_< length > ){
+
+ typedef typename tuples::element< index, TTuple>::type element_type;
+
+ object element = py_sequence[index];
+ c_tuple.template get< index >() = extract<element_type>( element );
+
+ construct_impl( py_sequence, c_tuple, details::increment_index<index>(), length_type() );
+ }
+
+ template< int length >
+ static void
+ construct_impl( const python::object& py_sequence, TTuple& c_tuple, mpl::int_< length >, mpl::int_< length > )
+ {}
+
+};
+
+template< class TTuple>
+void register_tuple(){
+
+ to_python_converter< TTuple, to_py_tuple<TTuple> >();
+
+ converter::registry::push_back( &from_py_sequence<TTuple>::convertible
+ , &from_py_sequence<TTuple>::construct
+ , type_id<TTuple>() );
+};
+
+} } //boost::python
+
+#endif//TUPLES_HPP_16_JAN_2007