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 NoneTypeNone
, 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 ifstr(val)
is not'None'
. An exception will be raised if the conversiondtype(str(val))
is not possible. The exact exception depends on val and dtype.empty_none (
bool
, optional) – IfTrue
, also convert val toNone
ifstr(val)
is the empty string''
.case_sensitive (
bool
, optional) – IfFalse
, also convert the lower case string'none'
to the NoneTypeNone
.
- Returns:
val (
None
ordtype
) – The input string, either converted toNone
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 passNone
to a script via the command line, because it will always render it as the string'None'
. Passlambda val: mdt.fh.str2none_or_type(val, dtype=<dtype>)
(where<dtype>
is e.g.float
orstr
) to the type keyword ofargparse.ArgumentParser.add_argument()
to convert the string'None'
(and optionally the empty string''
) to the NoneTypeNone
.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