Skip to main content

export - Convert expression to string in a reversible manner


What is the best way to convert an expression to a string in a reversible manner?


I need a toStr function so that it is always true that



ToExpression@toStr[expr] === expr

ToString is not satisfactory because it may use special, irreversible formatting. Example:


ToString[Graphics[{Circle[{0,0}]}]]
(* "-Graphics-" *)

In this case the problem is that it uses OutputForm by default. Requesting InputForm would solve this. But then consider


Format[x, InputForm] = "foo"

ToString[x, InputForm]

(* "foo" *)

x does exist as a proper expression in-memory. It can be written to disk by exporting to MX and then reliably re-imported. I am looking for the same functionality, but through strings.




Note: I am aware that there are some expressions which can't be safely cycled through a string, or even through Compress or through MathLink. An example would be


asc = <| a -> 1|>
a = 5;

asc
(* <| a -> 1|> *)


ToExpression@ToString[asc] (* or use Uncompress@Compress[...] if you like *)
(* <| 5 -> 1 |> *)

I am not aiming to solve these types of difficulties, which are separate from my main problem.




Comments