This is not quite a response but a (politically incorrect) opinion.
Interchange formats
Both json modules, yaml, xml, ... contain functions that recognize the
respective formats (languages) and create a semantic representation
parser : STR -> objectoPythonEspecífico
and serialize prittyprint : objectoPythonEspecífico -> STR
being typically used for structured exchange structured between different
contexts (different sessions, processes, languages, machines, platforms).
ast.literal_eval
The ast.literal_eval
is somewhat similar in that the format is
a small subset of the Python language including
- constants (str, numbers, tuples, lists, dictionaries)
- You can use a set of "peaceful" operators.
Does not allow for example expressions containing:
(1) variables and functions,
(2) Indexing of tuples, lists, dictionaries.
The ast.literal_eval
is nonreflective.
eval
The eval(expressão)
, exec(strcodigo)
, are much more powerful:
allows all syntax
of Python expressions, allow
reflexivity: we can access and define new variables, functions, etc.
(in) Security
Fortunately you can do dangerous things with eval
, with Python,
with system()
, with bash
, with any powerful tool.
Of course miracles can also be performed.
The eval(str)
has to be used with caution when str
has origins
uncontrolled and potentially adverse. If str
is in some way
dependent on user interaction, the situation is as dangerous as
the user is dangerous.
eval(rawinput())
is precisely what we are running when we run
the Python interpreter - and this never put anyone to sleep. If we do
something analogous to a web application: ... it will go wrong!
I see no harm in using eval indiscriminately in my activities.
I defined a calculator that, like the Python interpreter, uses something
print(pp(eval(retoca(rawinput("?"))))
and that allows me fantastic things and also format the disk and everything!