[Tutor] Magic numbers
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Aug 5 05:32:19 EDT 2021
On 05/08/2021 07:31, Phil wrote:
> I'm in the process of tidying up a recent project which was littered
> with magic numbers. This line of code is called approximately 80 times
> per second:
>
> if variable-name < 128:
Using a named constant can make things more readable.
But in this case 128 is such a well known marker that I'd
argue it doesn't need to be changed. If it was a
slightly different number like 132 or something then
we'd like an explanation, but 128 is a commonly used
power of two.
Its like time calculations where we multiply by 60
or 24 - we all know how many minutes are in an hour
and hours in days so it isn't really necessary to
have constants called HOURS_IN_DAY etc.
On the other hand, if 128 is not being used as a
power-of-two marker and actually represents some
application value then is should definitely be
given a symbolic name.
> bit shifting calculations and so < 2 ** 7 does make sense
No it doesn't because you'd be doing the calculation
every time (although the optimiser might be clever
enough to spot that and create its own constant!) which
would be slow.... It would certainly be enough to wipe
out any theoretical advantage of using bit shifting...
> I could use a pre-calculated global constant.
You could, but for this specific case, 128 is so well
known that would not really be necessary.
> Python, a global constant might be the better option
Either global or local if only used in one function.
Also you could have a module of constants that you
import. If they are constants they should be upper
case so that is one case where
from myapp_constants import *
is safe to use.
Incidentally, why are you using bit shifting rather
than regular arithmetic? That should be a last
resort optimisation. It will make the code far less
readable than magic numbers! So unless you have tested
the code using regular arithmetic and found it runs
slow and profiling the code has identified that it
is the arithmetic that is slowing it down, then
there is no sane reason to use bit-shifting!
Of course, if you are actually reading and processing
the individual bits of a piece of data then bit shifting
is entirely appropriate. But using it for arithmetic
is usually a fault-prone waste of everyone's time.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list