CIME.namelist.literal_to_python_value
- CIME.namelist.literal_to_python_value(literal, type_=None)[source]
Convert a Fortran literal string to a Python value.
This function assumes that the input contains a single value, i.e. repetition syntax is not used. The type can be specified by passing a string as the type_ argument, or if this option is not provided, this function will attempt to autodetect the variable type.
Note that it is not possible to be certain whether a literal like “123” is intended to represent an integer or a floating-point value, however, nor can we be certain of the precision that will be used to hold this value in actual Fortran code. We also cannot use the optional information in a NaN float, so this will cause the function to throw an error if that information is present (e.g. a string like “NAN(1234)” will cause an error).
The Python type of the return value is as follows for different type_ arguments: “character” - str “complex” - complex “integer” - int “logical” - bool “real” - float
If a null value is input (i.e. the empty string), None will be returned.
>>> literal_to_python_value("'She''s a winner!'") "She's a winner!" >>> literal_to_python_value("1") 1 >>> literal_to_python_value("1.") 1.0 >>> literal_to_python_value(" (\n 1. , 2. )\n ") (1+2j) >>> literal_to_python_value(".true.") True >>> literal_to_python_value("Fortune") False >>> literal_to_python_value("bacon") Traceback (most recent call last): ... CIMEError: ERROR: 'bacon' is not a valid literal for any Fortran type. >>> literal_to_python_value("1", type_="real") 1.0 >>> literal_to_python_value("bacon", type_="logical") Traceback (most recent call last): ... CIMEError: ERROR: 'bacon' is not a valid literal of type 'logical'. >>> literal_to_python_value("1", type_="booga") Traceback (most recent call last): ... CIMEError: ERROR: Invalid Fortran type for a namelist: 'booga' >>> literal_to_python_value("2*1") Traceback (most recent call last): ... CIMEError: ERROR: Cannot use repetition syntax in literal_to_python_value >>> literal_to_python_value("") >>> literal_to_python_value("-1.D+10") -10000000000.0 >>> literal_to_python_value("nan(1234)") Traceback (most recent call last): ... ValueError: could not convert string to float: 'nan(1234)'