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

Parse comma-separated list as python list #39

Merged
merged 5 commits into from
Jul 25, 2024
Merged
Changes from 1 commit
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
Next Next commit
Add support to parse bash array as python array
Adds the capability to parse a bash array in a configuration as a
python array.

Note: since arrays cannot reliably be exported in shell, such variables
should only be used locally in a config or by python that is parsing it.
  • Loading branch information
WalterKolczynski-NOAA committed Jul 25, 2024
commit e553a326b8e53938c423e8d24192962b5eb6bb67
11 changes: 8 additions & 3 deletions src/wxflow/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,23 @@ def cast_strdict_as_dtypedict(ctx: Dict[str, str]) -> Dict[str, Any]:
def cast_as_dtype(string: str) -> Union[str, int, float, bool, Any]:
"""
Cast a value into known datatype

Parameters
----------
string: str

Returns
-------
value : str or int or float or datetime
value : str, int, float, bool or datetime; or List of these
default: str
"""
TRUTHS = ['y', 'yes', 't', 'true', '.t.', '.true.']
BOOLS = ['n', 'no', 'f', 'false', '.f.', '.false.'] + TRUTHS
BOOLS = [x.upper() for x in BOOLS] + BOOLS + ['Yes', 'No', 'True', 'False']

def _cast_or_not(type: Any, string: str):
def _cast_or_not(to_type: Any, string: str):
DavidHuber-NOAA marked this conversation as resolved.
Show resolved Hide resolved
try:
return type(string)
return to_type(string)
except ValueError:
return string

Expand All @@ -185,6 +187,9 @@ def _true_or_not(string: str):
except Exception as exc:
if string in BOOLS: # Likely a boolean, convert to True/False
return _true_or_not(string)
elif string.startswith('(') and string.endswith(')'):
# Convert bash array to python array
return [ cast_as_dtype(elem) for elem in string[1:-1].split() ]
elif '.' in string: # Likely a number and that too a float
return _cast_or_not(float, string)
else: # Still could be a number, may be an integer
Expand Down