Skip to main content

Oneliner-izer

Build Status

Convert any Python file into a single line of code which has the same functionality.

No newlines allowed. No semicolons allowed, either.

Live demo at onelinepy.herokuapp.com!

Presentation at PyCon 2016, and slide deck.

User Installation and Usage

Install via pip from PyPI:

$ pip install onelinerizer

Use either the command line function or the Python module:

$ echo "def f(x):\n    print x\nf(4)" > sandbox.py
$ onelinerizer sandbox.py --debug
$ onelinerizer sandbox_ol.py
from onelinerizer import onelinerize
onelinerize("def f(x):\n    print x\nf(4)")

Examples

Before:

x = 3
y = 4
print (x < y < 5)

After:

(lambda __builtin__: (lambda __print, __y, d: [[__print(d.x<d.y<5) for d.y in [(4)]][0] for d.x in [(3)]][0])(__builtin__.__dict__['print'],(lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))),type('StateDict',(),__builtin__.__dict__)()))(__import__('__builtin__'))

That line looks complicated, because we need some tricks to import the print function and to support certain tricks which are needed for more complicated features such as while and if. For a program as simple as this one, though, you can think of it as working this way:

(lambda x: (lambda y: print(x<y<5))(4))(3)

Before:

def f(x):
    return x+5
print f(13)

After:

(lambda __builtin__: (lambda __print, __y, d: [__print(d.f(13)) for d.f in [(lambda x:[(d.x+5) for d.x in [(x)]][0])]][0])(__builtin__.__dict__['print'],(lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))),type('StateDict',(),__builtin__.__dict__)()))(__import__('__builtin__'))

...or, if you want to think about something more simplified:

(lambda f: print(f(13)))(lambda x: x+5)

Before:

def guess_my_number(n):
    while True:
        user_input = raw_input("Enter a positive integer to guess: ")
        if len(user_input)==0 or not user_input.isdigit():
            print "Not a positive integer!"
        else:
            user_input = int(user_input)
            if user_input > n:
                print "Too big! Try again!"
            elif user_input < n:
                print "Too small! Try again!"
            else:
                print "You win!"
                return True
guess_my_number(42)

After:

(lambda __builtin__: (lambda __print, __y, d: [(lambda ___: None)(d.guess_my_number(42)) for d.guess_my_number in [(lambda n:[(__y(lambda __this: (lambda d: (lambda __after: [(lambda __after: (lambda ___: __after(d))(__print('Not a positive integer!')) if (d.len(d.user_input)==0 or (not d.user_input.isdigit())) else [(lambda __after: (lambda ___: __after(d))(__print('Too big! Try again!')) if d.user_input>d.n else (lambda __after: (lambda ___: __after(d))(__print('Too small! Try again!')) if d.user_input<d.n else (lambda ___: d.True)(__print('You win!')))(lambda d: __after(d)))(lambda d: __after(d)) for d.user_input in [(d.int(d.user_input))]][0])(lambda d: __this(d)) for d.user_input in [(d.raw_input('Enter a positive integer to guess: '))]][0] if d.True else __after(d))(lambda d: None))))(d) for d.n in [(n)]][0])]][0])(__builtin__.__dict__['print'],(lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))),type('StateDict',(),__builtin__.__dict__)()))(__import__('__builtin__'))

FAQ

Oh dear God why?

Yeah. I'm sorry. But on the other hand, why not?

Can't you use semicolons?

That would be against the spirit of this exercise. Why pass up a perfectly good excuse to abuse lambda functions, ternary expressions, list comprehensions, and even the occasional Y combinator? Never pass up an opportunity to use the Y combinator.

Analysis

Output program size

O(n). No code is ever duplicated, so the one-lined code produced is linear in the size of the input code.

Runtime of one-lined code

I have no reason to believe the resulting code, however absurd, is more than a constant factor slower than the original code. Since while loops, etc. are implemented using recursive function calls, causing more overhead for setting up those function calls, the constant factor is likely to be somewhat bad.

Tips

The one-lined code tends to contain many nested lambdas; if there are too many, Python will refuse to run it.

$ python main_ol.py
s_push: parser stack overflow
MemoryError

This can be fixed using pypy.

$ pypy main_ol.py

However, since while loops and for loops are implemented with recursion, you might encounter maximum recursion depth exceeded errors during runtime if your loops go on for too long.

To get around this, you can put

import sys
sys.setrecursionlimit(new_limit)

in your original Python code. (onelinerizer will not place this command in for you.)

Not Implemented

  • from foo import *

Open Problems

  • with
  • yield

Developer Installation and Testing

$ git clone https://github.com/csvoss/onelinerizer
$ cd onelinerizer
$ python -m onelinerizer .setup.py setup.py
$ python setup.py test

To install the local module:

$ pip install .

Further Reading

Metadata

Release files for onelinerizer 1.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for onelinerizer 1.0.4
File Size Uploaded
onelinerizer-1.0.4.tar.gz 13.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for onelinerizer 1.0.4
File Interpreter ABI Platform
onelinerizer-1.0.4-py2-none-any.whl Python 2 none any Details

Total release size: 27.2 kB

Release files / onelinerizer-1.0.4.tar.gz

Download URL onelinerizer-1.0.4.tar.gz
Size 13.0 kB
Tags Source
SHA-256 checksum
How to use checksums
9b5d8e774489e8abeb440150b773965a76da907ef748cbf1bf3b77a3cdc1f11f
BLAKE2b-256 checksum
How to use checksums
9f3d7863505e71baa78e68e8f289e5b7e9251a03acd9e701cc91a36c729ef118
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / onelinerizer-1.0.4-py2-none-any.whl

Download URL onelinerizer-1.0.4-py2-none-any.whl
Size 14.1 kB
Tags Python 2
SHA-256 checksum
How to use checksums
f788266b8cd3183599a6fb0dfe9e4a65efc942338f33a4f76a0499b212bd460a
BLAKE2b-256 checksum
How to use checksums
25622753676d57bab0d4999b9c14695351f80ab7802c56f30fc1a377edb5808f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

1.0.4 This release

2 release files

1.0.3

2 release files

1.0.2

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page