Skip to content
Open
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
19 changes: 16 additions & 3 deletions launch/launch/substitutions/python_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,22 @@ def __init__(self, expression: SomeSubstitutionsType,
def parse(cls, data: Sequence[SomeSubstitutionsType]
) -> Tuple[Type['PythonExpression'], Dict[str, Any]]:
"""Parse `PythonExpression` substitution."""
if len(data) < 1 or len(data) > 2:
raise TypeError('eval substitution expects 1 or 2 arguments')
kwargs = {'expression': data[0]}
if len(data) < 1:
raise TypeError('eval substitution expects at least 1 argument')
kwargs: Dict[str, Any] = {}
if len(data) <= 2:
kwargs['expression'] = data[0]
else:
# The expression is split into multiple arguments when it contains
# spaces, e.g. `$(eval 1 == 1)`.
# Join the arguments back with spaces to recover the expression.
from ..utilities import normalize_to_list_of_substitutions
expression: List[Substitution] = []
for i, sub_expression in enumerate(data):
if i > 0:
expression += normalize_to_list_of_substitutions(' ')
expression += normalize_to_list_of_substitutions(sub_expression)
kwargs['expression'] = expression
if len(data) == 2:
# We get a text substitution from XML,
# whose contents are comma-separated module names
Expand Down
17 changes: 17 additions & 0 deletions launch/test/launch/substitutions/test_python_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,20 @@ def test_python_substitution_submodule():

# The expression should evaluate to True
assert result


def test_python_substitution_parse_multiple_arguments():
"""Check that parse() joins an expression split across multiple arguments."""
lc = LaunchContext()

# The frontend splits an expression containing spaces, e.g. `$(eval 1 == 1)`
cls, kwargs = PythonExpression.parse(['1', '==', '1'])
subst = cls(**kwargs)
result = subst.perform(lc)

assert result == 'True'

# Test the describe() method
assert subst.describe() == (
"PythonExpr('1' + ' ' + '==' + ' ' + '1', ['math'])"
)