Python self-evaluating strings

Boris Borcic bborcic at gmail.com
Sun Jan 27 14:00:18 EST 2008


Now there's always that style :

 >>> print x

Traceback (most recent call last):
   File "<pyshell#15>", line 1, in <module>
     eval(x)
   File "<string>", line 2
     Traceback (most recent call last):
                          ^
SyntaxError: invalid syntax

 >>> eval(x)

Traceback (most recent call last):
   File "<pyshell#15>", line 1, in <module>
     eval(x)
   File "<string>", line 2
     Traceback (most recent call last):
                          ^
SyntaxError: invalid syntax
 >>>


Arnaud Delobelle wrote:
> Hi all,
> 
> An earlier post today got me thinking about "quines" (programs that 
> output themselves) in Python.  I tried to find some on the web but 
> didn't find many ([1]).  In particular I didn't find any that 
> corresponded to my instinctive (LISP-induced, probably) criterion:
> 
> def self_evaluating(s):
>     "Return True if string s evaluates to itself"
>     return s == eval(s)
> 
> Here is the result of my efforts so far:
> 
> 1. Starting from the classic idea (lambda x:x%x)('lambda x:x%x') I got 
> the following
> v=(lambda x:x%('"''""'+x+'"''""'))("""(lambda 
> x:x%%('"''""'+x+'"''""'))(%s)""")
> 
> 2. (Given that if s is a nonempty string, s*2 is a longer string).  
> Starting from the idea "%s %s" % (("%s %s",)*2) I got the following
> u="\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2)
> 
> Most of my problems in creating these 2 was with finding a suitable way 
> of quoting strings that propagates well. Both u and v are one-liners.  
> I'm hoping for no funky line wrapping here.
> 
> Note: I'm not quoting the string as it makes no difference since they 
> evaluate to themselves:)
> 
> I'd like to know if anyone on the list has indulged in this 
> time-bending/mind-wasting activity before.  If so, it would be nice to 
> create a list of such expressions.
> 
> Quining's-better-than-ironing'ly yours
> 
> --Arnaud
> 
> [1] http://www.nyx.net/~gthompso/self_pyth.txt
> 



More information about the Python-list mailing list