Sunday, January 17, 2010

Intuitive division in Python

When one is hot-coding some idea, it is all about writing down an idea fast, not pretty (even so it's quite hard to write ugly code in Python due to its indental paradigm), not clean or precise, just trying out an idea.
It is then that it could happen to overlook that a division of 2 integer numbers is forcing an integer solution of this calculation (the underlying C-paradigm for divisions in Python is enforcing this), so 3/4 is 0, not 0.75, because one forgot to write something like 3/4.0 to enforce the floating point division.
Many errors in un-counted Python (and C) classes were caused by this intricacy, maybe even some good ideas have been discredited because the code produced weird results. And because of the caused frustrations, the Python inventors have decided to get rid of this, beginning with the 3.x versions of Python, so 3/4 is actually 0.75.
And because this was such a great idea, it was decided to make it available as an option in Python 2.x (before you judge this as a minor change, admit to yourself how often you have been caught by this bug!?).
So, to enable this 'safe' division in Python 2.x code, you have to write the following line before all other imports:
from __future__ import division
(thats 2 underscores in front AND behind the future)

Enjoy your hot-coding now! ;)