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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With