Skip to content

Commit

Permalink
Evaluate math symbols and functions in python expression (#557) (#562)
Browse files Browse the repository at this point in the history
* Evaluate math symbols and functions in python expression

Signed-off-by: Immanuel Martini <[email protected]>
Co-authored-by: Jacob Perron <[email protected]>
  • Loading branch information
martiniil and jacobperron authored Dec 22, 2021
1 parent 5fecaff commit 8c98866
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
4 changes: 3 additions & 1 deletion launch/launch/substitutions/python_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""Module for the PythonExpression substitution."""

import collections.abc
import math
from typing import Iterable
from typing import List
from typing import Text
Expand All @@ -33,6 +34,7 @@ class PythonExpression(Substitution):
The expression may contain Substitutions, but must return something that can
be converted to a string with `str()`.
It also may contain math symbols and functions.
"""

def __init__(self, expression: SomeSubstitutionsType) -> None:
Expand Down Expand Up @@ -67,4 +69,4 @@ def describe(self) -> Text:
def perform(self, context: LaunchContext) -> Text:
"""Perform the substitution by evaluating the expression."""
from ..utilities import perform_substitutions
return str(eval(perform_substitutions(context, self.expression)))
return str(eval(perform_substitutions(context, self.expression), {}, math.__dict__))
8 changes: 8 additions & 0 deletions launch/test/launch/frontend/test_substitutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ def test_eval_subst():
assert 'asdbsd' == expr.perform(LaunchContext())


def test_eval_subst_of_math_expr():
subst = parse_substitution(r'$(eval "ceil(1.3)")')
assert len(subst) == 1
expr = subst[0]
assert isinstance(expr, PythonExpression)
assert '2' == expr.perform(LaunchContext())


def expand_cmd_subs(cmd_subs: List[SomeSubstitutionsType]):
return [perform_substitutions_without_context(x) for x in cmd_subs]

Expand Down

0 comments on commit 8c98866

Please sign in to comment.