Skip to content

Commit

Permalink
[feat] Parse convertible mapping objects with json module
Browse files Browse the repository at this point in the history
The advantage is that we can automatically convert nested mappings, like for
example the `extra_resources` attribute, which can thus be set from the command
line.
  • Loading branch information
giordano committed May 2, 2023
1 parent 45675f9 commit 63fdda5
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions reframe/utility/typecheck.py
Expand Up @@ -95,6 +95,7 @@

import abc
import datetime
import json
import re


Expand Down Expand Up @@ -320,21 +321,12 @@ def __getitem__(cls, typespec):

def __rfm_cast_str__(cls, s):
mappping_type = cls._type
key_type = cls._key_type
value_type = cls._value_type
seq = []
for key_datum in s.split(','):
try:
k, v = key_datum.split(':')
except ValueError:
# Re-raise as TypeError
raise TypeError(
f'cannot convert string {s!r} to {cls.__name__!r}'
) from None

seq.append((key_type(k), value_type(v)))

return mappping_type(seq)
# Convert string to JSON format: wrap it with braces and add double
# quotes where necessary.
s = f'{{{s}}}'
s = re.sub('([:,{] *)([^":,{}]+)', r'\1"\2"', s)
# Parse the JSON string and convert to the desired mapping type.
return mappping_type(json.loads(s))


class _StrType(_SequenceType):
Expand Down

0 comments on commit 63fdda5

Please sign in to comment.