From f6f25c9192d029862d9d0f97f1e02c07896e62b2 Mon Sep 17 00:00:00 2001 From: Tom Wiesing Date: Thu, 21 May 2020 14:34:34 +0200 Subject: [PATCH 1/2] Convert range() objects using 'integer_interval' from cd 'interval1' This issue adds translation for the range() class to the DefaultConverter. Note that a python range(start, stop) does not include the value of stop, whereas the 'integer_interval' symbol does. The converter thus has to add or subtract one. Fixes #29. --- openmath/convert.py | 9 +++++++++ tests/test_convert.py | 1 + 2 files changed, 10 insertions(+) diff --git a/openmath/convert.py b/openmath/convert.py index 5074e23..f59bda9 100644 --- a/openmath/convert.py +++ b/openmath/convert.py @@ -259,6 +259,7 @@ class BasicPythonConverter(Converter): - complex numbers (recursively), - strings, - bytes, + - ranges, - lists (recursively), - sets (recursively). """ @@ -278,6 +279,8 @@ def __init__(self): r('set1', 'set', lambda *args: set(args)) r('list1', 'list', lambda *args: list(args)) r('complex1', 'complex_cartesian', complex) # this does not work if the arguments are not numbers + r('interval1', 'integer_interval', lambda x,y: range(x, y + 1, 1)) + # literals s = self.register_to_python_class s(om.OMInteger, lambda o: o.integer) @@ -311,6 +314,12 @@ def do_set(s): else: return oms('emptyset', cd='set1') t(set, do_set) + def do_range(r): + if r.step != 1: + raise ValueError('Cannot convert %r to OpenMath: Range must have a step of 1. ' % obj) + return om.OMApplication(oms('integer_interval', 'interval1'), [om.OMInteger(r.start), om.OMInteger(r.stop - 1)]) + t(range, do_range) + # A default converter instance for convenience diff --git a/tests/test_convert.py b/tests/test_convert.py index 13708c0..2f6f86b 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -15,6 +15,7 @@ def test_py_om_py(self): "", "test", [], [1,2,3], set(), set([1,2,3]), + range(1, 12) ] for obj in testcases: conv = DefaultConverter.to_python(DefaultConverter.to_openmath(obj)) From c0387695631c6ec0dac1361aae5ed6e0578cbd0a Mon Sep 17 00:00:00 2001 From: Tom Wiesing Date: Fri, 22 May 2020 13:34:57 +0200 Subject: [PATCH 2/2] Update README with range() conversion --- README.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/README.rst b/README.rst index f54b863..674c0cb 100644 --- a/README.rst +++ b/README.rst @@ -66,6 +66,7 @@ By default, a ``Converter`` only implements conversions for basic Python types: - complex numbers, - strings, - bytes, +- ranges, - lists (recursively), - sets (recursively).