Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Python code be compressed like Javascript?

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.

like image 234
Jace Cotton Avatar asked Oct 02 '22 14:10

Jace Cotton


1 Answers

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.

like image 164
reem Avatar answered Oct 13 '22 00:10

reem