Shukai Ni
Shukai Ni

Reputation: 467

Python opposite of eval()

Is it possible to do the opposite of eval() in python which treats inputs as literal strings? For example f(Node(2)) -> 'Node(2)' or if there's some kind of higher-order operator that stops interpreting the input like lisp's quote() operator.

Upvotes: 1

Views: 842

Answers (1)

phipsgabler
phipsgabler

Reputation: 20950

The answer to does Python have quote is no, Python does not have quote. There's no homoiconicity, and no native infrastructure to represent the languages own source code.

Now for what is the opposite of eval: you seem to be missing some part the picture here. Python's eval is not the opposite of quote. There's three types values can be represented as: as unparsed strings, as expressions, and as values (of any type).

  • quote and LISP-style "eval" convert between expressions and values.
  • Parsing and pretty printing form another pair between expressions and strings.
  • Python's actual eval goes directly from strings to values, and repr goes back (in the sense of printing a parsable value1).

Since SO does not support drawing diagrams:

enter image description here

So if you are looking for the opposite of eval, it's either trivially repr, but that might not really help you, or it would be the composition of quote and pretty priniting, if there were quoting in Python.

This composition with string functions a bit cumbersome, which is why LISPs let the reader deal with parsing once and for all, and from that point on only go between expressions and values. I don't know any language that has such a "quote + print" function, actually (C#'s nameof comes close, but is restricted to names).

Some caveats about the diagram:

  1. It does not commute: you have deal with pure values or disregard side effects, for one, and most importantly quote is not really a function in some sense, of course. It's a special form. That's why repr(x) is not the same as prettyprint(quote(x)), in general.
  2. It's not depicting pairs of isomorphisms. Multiple expressions can eval to the same value etc.

1That's not always the case in reality, but that's what it's suppsedly there for.

Upvotes: 3

Related Questions