Search code examples
pythonabstract-syntax-treestring-parsing

What is the best way to parse a tuple from a string in Python?


I tried this:

def string_to_value(self, old_value, distribution_type, new_value_str):
    parameter_names = distribution_type.parameters  # a list of string
    try:
        parameter_values = ast.literal_eval(new_value_str)  # a tuple or basic type hopefully
    except SyntaxError:
        raise ValueError('Syntax error during parse')
    retval = copy.copy(old_value)
    try:
        if len(parameter_names) == 1:
            setattr(retval, parameter_names[0], parameter_values)
        else:
            if len(parameter_names) != len(parameter_values):
                raise BoostPythonArgumentError
            for parm_name, parm_value in zip(parameter_names,
                                             parameter_values):
                setattr(retval, parm_name, parm_value)
    except BoostPythonArgumentError:
        raise ValueError('Lots of helpful text here')
    return retval

This works for a lot of cases. Boost.Python automatically checks the type of parm_value at set time. Unfortunately, it doesn't work on strings containing 'inf'. ast.literal_eval raises ValueError('malformed string') when I would like it to return a float. I don't understand how Python can parse 'inf', but literal_eval can't.


Solution

  • Check this documentation and this PEP about evaluating inf. I guess they will help