Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Galactic] Evaluate math symbols and functions in python expression (#557) #563

Merged
merged 1 commit into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
hidmic marked this conversation as resolved.
Show resolved Hide resolved
"""

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