Skip to content

Commit f63717b

Browse files
authored
Merge pull request #1918 from OpenC3/python_multi_line_generic_conversion
Fix multi line generic conversions in Python
2 parents 41264af + d5eca55 commit f63717b

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

openc3/python/openc3/conversions/generic_conversion.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,18 @@ def __init__(
5050
self.converted_array_size = int(converted_array_size)
5151
self.params = [code_to_eval, converted_type, converted_bit_size, converted_array_size]
5252

53+
# Setup multiline eval where the last line defines the return value for eval
54+
lines = code_to_eval.splitlines()
55+
exec_lines = lines[0:(len(lines) - 1)]
56+
self.exec_lines = compile("\n".join(exec_lines), "<string>", "exec")
57+
self.eval_line = compile(lines[-1], "<string>", "eval")
58+
5359
def call(self, value, packet, buffer):
5460
myself = packet # For backwards compatibility
5561
if myself: # Remove unused variable warning for myself
56-
return eval(self.code_to_eval)
62+
generic_globals = {"value": value, "myself": myself, "packet": packet, "buffer": buffer}
63+
exec(self.exec_lines, generic_globals)
64+
return eval(self.eval_line, generic_globals)
5765

5866
# self.return [String] The conversion class followed by the code to evaluate
5967
def __str__(self):

openc3/python/test/conversions/test_generic_conversion.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,11 @@ def test_creates_a_reproducable_format(self):
5252
self.assertEqual(gc.converted_array_size, (new_gc.converted_array_size))
5353
self.assertEqual(gc.call(0, pkt, 0), 5.0)
5454
self.assertEqual(new_gc.call(0, pkt, 0), 5.0)
55+
56+
def test_multiple_lines(self):
57+
gc = GenericConversion("x = 10\ny = 2\nx / y", "UINT", 8)
58+
self.assertEqual(gc.call(0, Packet(None, None), 0), 5)
59+
gc = GenericConversion("x = 10\ny = 2\nx / y / value", "UINT", 8)
60+
self.assertEqual(gc.call(5, Packet(None, None), 0), 1)
61+
gc = GenericConversion("import math\nx = 10\ny = 2\nmath.ceil(x / y / value)", "UINT", 8)
62+
self.assertEqual(gc.call(2, Packet(None, None), 0), 3)

0 commit comments

Comments
 (0)