Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python optimized mode

Tags:

python

Python can run script in optimized mode (-O) that turns off debugs like assert and if I remember also remove docstrings. I have no seen it used really and maybe it is just artifact of the past times. Is it being used? What for?

Why isn't this useless thing being removed in Python 3?

like image 414
zaharpopov Avatar asked Jan 13 '10 09:01

zaharpopov


People also ask

What is Python optimized for?

Python code optimization is a way to make your program perform any task more efficiently and quickly with fewer lines of code, less memory, or other resources involved, while producing the right results. It's crucial when it comes to processing a large number of operations or data while performing a task.

Does Python have compiler optimization?

Accelerate Python FunctionsNumba translates Python functions to optimized machine code at runtime using the industry-standard LLVM compiler library. Numba-compiled numerical algorithms in Python can approach the speeds of C or FORTRAN.


2 Answers

python -O does the following currently:

  • completely ignores asserts
  • sets the special builtin name __debug__ to False (which by default is True)

and when called as python -OO

  • removes docstrings from the code

I don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.

like image 199
tzot Avatar answered Sep 17 '22 15:09

tzot


It saves a small amount of memory, and a small amount of disk space if you distribute any archive form containing only the .pyo files. (If you use assert a lot, and perhaps with complicated conditions, the savings can be not trivial and can extend to running time too).

So, it's definitely not useless -- and of course it's being used (if you deploy a Python-coded server program to a huge number N of server machines, why ever would you want to waste N * X bytes to keep docstrings which nobody, ever, would anyway be able to access?!). Of course it would be better if it saved even more, but, hey -- waste not, want not!-)

So it's pretty much a no-brainer to keep this functionality (which is in any case trivially simple to provide, you know;-) in Python 3 -- why add even "epsilon" to the latter's adoption difficulties?-)

like image 23
Alex Martelli Avatar answered Sep 20 '22 15:09

Alex Martelli