Skip to content

Commit 95386e5

Browse files
committed
python: add convert_values member to ConstraintParser class
Problem: Values are always returned as strings by the ConstraintParser parser, but there are times when another type may be more suitable. Additionally, there is currently no way to reduce a set of values to a single element if this is required or beneficial in the result. Add a convert_values mapping to the ConstraintParser class. If an operator is in this dictionary, then the values of a term are passed to the provided callable, which should return a new list of values as a result.
1 parent 8e9a03d commit 95386e5

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/bindings/python/flux/constraint/parser.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,16 @@ class default operator may optionally be substituted, e.g. "operand"
231231
to split values of that operator. For instance ``{"op": ","}``
232232
would autosplit operator ``op`` values on comma.
233233
234+
convert_values (dict): A mapping of operator name to callable which
235+
should take a single list argument containing the values from
236+
the obtained from the current term for the operator after the
237+
operator_map and split_values operations have been applied. The
238+
callable should return a new list of values. This can be used
239+
to convert values to a new type or to combine multiple values
240+
into a single element, e.g. ::
241+
242+
convert_values = {"ints": lambda args: [int(x) for x in args]}
243+
234244
combined_terms (set): A set of operator terms whose values can be
235245
combined when joined with the AND logical operator. E.g. if
236246
"test" is in ``combined_terms``, then
@@ -284,6 +294,10 @@ class MyConstraintParser(ConstraintParser):
284294
# Combined terms
285295
combined_terms = set()
286296

297+
# Mapping of operator name to value conversion function.
298+
# E.g. { "integer": lambda args: [ int(x) for x in args ] }
299+
convert_values = {}
300+
287301
def __init__(
288302
self, lexer=None, optimize=True, debug=False, write_tables=False, **kw_args
289303
):
@@ -408,10 +422,12 @@ def p_expression_token(self, p):
408422
f"invalid character '{invalid}' in operator '{op}:'"
409423
)
410424

425+
values = [value]
411426
if op in self.split_values:
412-
p[0] = {op: value.split(self.split_values[op])}
413-
else:
414-
p[0] = {op: [value]}
427+
values = value.split(self.split_values[op])
428+
if op in self.convert_values:
429+
values = self.convert_values[op](values)
430+
p[0] = {op: values}
415431

416432
def p_quoted_token(self, p):
417433
"""

0 commit comments

Comments
 (0)