Skip to content

Instantly share code, notes, and snippets.

@garcia
Last active December 12, 2015 09:39
Show Gist options
  • Save garcia/4753030 to your computer and use it in GitHub Desktop.
Save garcia/4753030 to your computer and use it in GitHub Desktop.
A one-liner that converts any Python script to a one-liner. There are no literal semicolons in this script or its output (i.e. it doesn't cheat).
print'exec '+(lambda L,R:lambda C:R(L,R,C))((lambda L,R,c:'type((lambda:0).__code__)(%s)'%','.join(R(L,R,getattr(c,'co_'+n))for n in'argcount:nlocals:stacksize:flags:code:consts:names:varnames:filename:name:firstlineno:lnotab:freevars:cellvars'.split(':'))),(lambda L,R,o:L(L,R,o)if type(o).__name__=='code'else'('+''.join(R(L,R,n)+','for n in o)+')'if type(o).__name__=='tuple'else repr(o)))((lambda n:compile(open(n,'r').read(),n,'exec'))(__import__('sys').argv[-1]))
# The outermost lambda receives two lambdas, L and R
# Because we're doing this all in one line, L and R must be passed
# as arguments to each other for all recursive calls
print 'exec ' + (lambda L, R:
# The inner lambda receives a code object...
lambda C:
# ...and passes it to R
R(L, R, C)
)(
# lambda L(c): converts c to a Python statement that constructs it
(lambda L, R, c:
# type((lambda:0).__code__) returns <type 'CodeType'> which is otherwise inaccessible
'type((lambda:0).__code__)(%s)' % ','.join(
R(L, R, getattr(c, 'co_' + n)) for n in
# CodeType requires a lot of arguments; only the last two are optional
('argcount:nlocals:stacksize:flags:code:' +
'consts:names:varnames:filename:name:' +
'firstlineno:lnotab:freevars:cellvars').split(':')
)
),
# lambda R(o): repr(o), unless o is code, in which case L(o)
(lambda L, R, o:
L(L, R, o) if type(o).__name__ == 'code'
else '(' + ''.join(R(L, R, n) + ',' for n in o) + ')' if type(o).__name__ == 'tuple'
else repr(o)
)
# This is the code object sent to the inner lambda
)((lambda n:
compile(open(n, 'r').read(), n, 'exec')
# Get program name from the last argument
)(__import__('sys').argv[-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment