Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like a reverse eval() function?

Tags:

python

eval

Imagine the following problem: you have a dictionary of some content in python and want to generate python code that would create this dict. (which is like eval but in reverse) Is there something that can do this?

Scenario: I am working with a remote python interpreter. I can give source files to it but no input. So I am now looking for a way to encode my input data into a python source file.

Example:

d = {'a': [1,4,7]}
str_d = reverse_eval(d)
# "{'a': [1, 4, 7]}"
eval(str_d) == d
like image 278
Christian Avatar asked Mar 25 '19 10:03

Christian


2 Answers

repr(thing)

will output text that when executed will (in most cases) reproduce the dictionary.

like image 169
David Jones Avatar answered Sep 22 '22 10:09

David Jones


Actually, it's important for which types of data do you want this reverse function to exist. If you're talking about built-in/standard classes, usually their .__repr__() method returns the code you want to access. But if your goal is to save something in a human-readable format, but to use an eval-like function to use this data in python, there is a json library. It's better to use json for this reason because using eval is not safe. Json's problem is that it can't save any type of data, it can save only standard objects, but if we're talking about not built-in types of data, you never know, what is at their .__repr__(), so there's no way to use repr-eval with this kind of data

So, there is no reverse function for all types of data, you can use repr-eval for built-in, but for built-in data the json library is better at least because it's safe

like image 44
Kolay.Ne Avatar answered Sep 19 '22 10:09

Kolay.Ne