str2none_or_type

mdtools.file_handler.str2none_or_type(val, dtype, empty_none=False, case_sensitive=True)[source]

Convert a string to the NoneType None or to a given type.

If the input string is 'None', convert it to the NoneType None, else convert it to the type given by dtype.

Parameters:
  • val (str_like) – The input value. Can be anything that can be converted to a string.

  • dtype (type) – The type to which val should be converted if str(val) is not 'None'. An exception will be raised if the conversion dtype(str(val)) is not possible. The exact exception depends on val and dtype.

  • empty_none (bool, optional) – If True, also convert val to None if str(val) is the empty string ''.

  • case_sensitive (bool, optional) – If False, also convert the lower case string 'none' to the NoneType None.

Returns:

val (None or dtype) – The input string, either converted to None or to dtype.

See also

mdtools.file_handler.str2bool()

Convert a string to a boolean value

Notes

This function was written to enable passing None to scripts via the command line. By default, argparse reads command-line arguments as simple strings. This makes it impossible to pass None to a script via the command line, because it will always render it as the string 'None'. Pass lambda val: mdt.fh.str2none_or_type(val, dtype=<dtype>) (where <dtype> is e.g. float or str) to the type keyword of argparse.ArgumentParser.add_argument() to convert the string 'None' (and optionally the empty string '') to the NoneType None.

References

This code was adapted from https://stackoverflow.com/a/55063765.

Examples

>>> mdt.fh.str2none_or_type('None', dtype=str)  # Returns None
>>> mdt.fh.str2none_or_type(None, dtype=str)  # Returns None
>>> mdt.fh.str2none_or_type('none', dtype=str)
'none'
>>> mdt.fh.str2none_or_type('none', dtype=str, case_sensitive=False)  # Returns None
>>> mdt.fh.str2none_or_type('', dtype=str)
''
>>> mdt.fh.str2none_or_type('', dtype=str, empty_none=True)  # Returns None
>>> mdt.fh.str2none_or_type(2, dtype=str)
'2'
>>> mdt.fh.str2none_or_type('None', dtype=int)  # Returns None
>>> mdt.fh.str2none_or_type('2', dtype=int)
2
>>> mdt.fh.str2none_or_type(2, dtype=int)
2
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     '--spam',
...     type=lambda val: mdt.fh.str2none_or_type(val, dtype=str)
... )
_StoreAction(option_strings=['--spam'], dest='spam', ...)
>>> parser.add_argument('--eggs', type=str)
_StoreAction(option_strings=['--eggs'], dest='eggs', ...)
>>> args = parser.parse_args(['--spam', 'None', '--eggs', 'None'])
>>> args.spam is None
True
>>> args.eggs is None
False
>>> args.eggs == 'None'
True