Skip to content

Missing validation for allowed constant values in ast.literal_eval() #141778

@skirpichev

Description

@skirpichev

Bug report

Bug description:

Maybe it's a feature, but I see something wrong here:

>>> import ast
>>> value = object()
>>> value
<object object at 0x7f7489580880>
>>> node = ast.Expression(body=ast.Constant(value))
>>> ast.fix_missing_locations(node)
Expression(body=Constant(value=<object object at 0x7f7489580880>, kind=None))
>>> ast.literal_eval(node)
<object object at 0x7f7489580880>
>>> compile(node, "<test>", "eval")
Traceback (most recent call last):
  File "<python-input-6>", line 1, in <module>
    compile(node, "<test>", "eval")
    ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: got an invalid type in Constant: object

Note, that for unary/binary ops values are checked, e.g.:

>>> node = ast.Expression(body=ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value)))
>>> ast.fix_missing_locations(node)
Expression(body=UnaryOp(op=USub(), operand=Constant(value=<object object at 0x7f7489580880>, kind=None)))
>>> ast.literal_eval(node)
Traceback (most recent call last):
  File "<python-input-10>", line 1, in <module>
    ast.literal_eval(node)
    ~~~~~~~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.14/ast.py", line 106, in literal_eval
    return _convert(node_or_string)
  File "/usr/local/lib/python3.14/ast.py", line 105, in _convert
    return _convert_signed_num(node)
  File "/usr/local/lib/python3.14/ast.py", line 74, in _convert_signed_num
    operand = _convert_num(node.operand)
  File "/usr/local/lib/python3.14/ast.py", line 70, in _convert_num
    _raise_malformed_node(node)
    ~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.14/ast.py", line 67, in _raise_malformed_node
    raise ValueError(msg + f': {node!r}')
ValueError: malformed node or string on line 1: Constant(value=<object object at 0x7f7489580880>, kind=None)
>>> compile(node, "<test>", "eval")
Traceback (most recent call last):
  File "<python-input-11>", line 1, in <module>
    compile(node, "<test>", "eval")
    ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: got an invalid type in Constant: object

(Tested in the main branch too.)

CPython versions tested on:

CPython main branch, 3.14

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixes3.14bugs and security fixes3.15new features, bugs and security fixesdocsDocumentation in the Doc dirstdlibStandard Library Python modules in the Lib/ directory

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions