Question

I am wondering if Python code can be compressed/non-human readable like Javascript can. I know indentions are important in Python, and it's core philosophy is readability, but is there, by any chance, a method that allows compressed Python code? Python 2.7, by the way.

Was it helpful?

Solution

There are a few different approaches you can take here.

Python does in fact offer opportunities for minification in the form of ;. A little known and little used (thankfully) syntactical element in python is that multiple expressions can be written on one line if ; is used.

For instance:

 if x > y:
     x += y
     print y
 else:
     y += x
     print x

Could be compressed to:

 if x>y:x+=y;print y;
 else:y+=x;print x;

There are tons of examples of this, you can also remove comments, and obfuscate simple code further with ternary operators. The ; gets rid of a ton of whitespace, but there are lots of smaller optimizations that can be made.

For some examples of libraries that do this for you, see here, here, or here.

Keep in mind that none of these are going to completely obfuscate your code to the point that it can't be recovered. Any sufficiently motivated person will be able to reverse-engineer your source code, even if undocumented, from this.

This remains true even if you only distribute .pyo or .pyc files. Python bytecode is usually not much smaller than the source code used to generate it, and can for the most part be easily reverse-engineered. Do not make the mistake of thinking that distributing a .pyc will completely secure your source code.

EDIT: If you are looking to package these as standalone binary executables, you might want to take a look at cx_Freeze. It could be closer to what you are looking for and much harder if not impossible to reverse-engineer.

OTHER TIPS

Unlike javascript which is usually executed by browsers and we must provide raw javascript source code.

You don't have to ship python codes, you can ship compiled binary files. There are many tool to do the work e.g. py2exe, Pyinstaller, cx_Freeze. Clients also benefit because they don't need to install Python or even know anything about Python.

Though the compiled Python code are easier to be decompiled comparing to java, c, c++ codes, but better than compressed source code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top