'Catching SyntaxError from ast.literal_eval

I have the following code to evaluate some configuration values stored in a file:

from ast import literal_eval

for key, value in dict_read_from_file.items():
    try:
        cfg[key] = literal_eval(value)
    except ValueError:
        cfg[key] = value

However, with certain inputs literal_eval raises a SyntaxError, rather than a ValueError:

>>> literal_eval('asdf')
Traceback (most recent call last):
    [...]
ValueError: malformed node or string on line 1: <ast.Name object at 0x000001A065B69AE0>

>>> literal_eval('123 4')
Traceback (most recent call last):
    [...]
File "ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
File "<unknown>", line 1
    123 4
        ^
SyntaxError: invalid syntax

But Python doesn't seem to let me catch the SyntaxError:

>>> try:
...     literal_eval('123 4')
... except ValueError | SyntaxError:
...     print("Fixing")
...

Traceback (most recent call last):
    [...]
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: catching classes that do not inherit from BaseException is not allowed

How do I catch and properly handle this SyntaxError?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source