Skip to content

Commit

Permalink
Merge pull request #606 from qutech/issues/604_expression_repr
Browse files Browse the repository at this point in the history
Fix expression repr
  • Loading branch information
terrorfisch committed Jul 8, 2021
2 parents 16bd4f2 + d42b2c7 commit 7cd11ee
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions changes.d/604.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `repr` of `ExpressionScalar` when constructed from a sympy expression. Also replace `Expression` with `ExpressionScalar` in `repr`.
5 changes: 4 additions & 1 deletion qupulse/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,10 @@ def __str__(self) -> str:
return str(self._sympified_expression)

def __repr__(self) -> str:
return 'Expression({})'.format(repr(self._original_expression))
if self._original_expression is None:
return f"ExpressionScalar('{self._sympified_expression!r}')"
else:
return f"ExpressionScalar({self._original_expression!r})"

def __format__(self, format_spec):
if format_spec == '':
Expand Down
19 changes: 18 additions & 1 deletion tests/expression_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys

import numpy as np
import sympy.abc
from sympy import sympify, Eq

from qupulse.expressions import Expression, ExpressionVariableMissingException, NonNumericEvaluation, ExpressionScalar, ExpressionVector
Expand Down Expand Up @@ -257,7 +258,23 @@ def test_evaluate_variable_missing(self) -> None:
def test_repr(self):
s = 'a * b'
e = ExpressionScalar(s)
self.assertEqual("Expression('a * b')", repr(e))
self.assertEqual("ExpressionScalar('a * b')", repr(e))

def test_repr_original_expression_is_sympy(self):
# in this case we test that we get the original expression back if we do
# eval(repr(e))

org = sympy.sympify(3.1415)
e = ExpressionScalar(org)
self.assertEqual(e, eval(repr(e)))

org = sympy.abc.a * sympy.abc.b
e = ExpressionScalar(org)
self.assertEqual(e, eval(repr(e)))

org = sympy.sympify('3/17')
e = ExpressionScalar(org)
self.assertEqual(e, eval(repr(e)))

def test_str(self):
s = 'a * b'
Expand Down
2 changes: 1 addition & 1 deletion tests/pulses/arithmetic_pulse_template_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ def test_repr(self):

with mock.patch.object(DummyPulseTemplate, '__repr__', wraps=lambda *args: 'dummy'):
r = repr(ArithmeticPulseTemplate(pt, '-', scalar))
self.assertEqual("(dummy - Expression('x'))", r)
self.assertEqual("(dummy - ExpressionScalar('x'))", r)

arith = ArithmeticPulseTemplate(pt, '-', scalar, identifier='id')
self.assertEqual(super(ArithmeticPulseTemplate, arith).__repr__(), repr(arith))
Expand Down

0 comments on commit 7cd11ee

Please sign in to comment.