[Tutor] Magic numbers

dn PyTutor at DancesWithMice.info
Thu Aug 5 02:43:55 EDT 2021


On 05/08/2021 18.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:
> 
> I'm doing bit shifting calculations and so  < 2 ** 7 does make sense or
> I could use a pre-calculated global constant. I'm thinking that, for
> Python, a global constant might be the better option or doesn't it
> matter and only adds an unnecessary complication making the code less
> readable.
> 
> It's not a matter of life or death, just wondering.


It would certainly be more efficient to use a constant, in preference to
re-calculating each time.

What is the "128" against which you are comparing the calculation?
If you can call it by some name, then give it that name, eg
fitting_in_seven_bits.

Is there some significance to the "128", eg maximum number of seats at a
conference venue? Then name it.

A name is a form of documentation because it contributes to (reader)
understanding!
-- 
Regards,
=dn


More information about the Tutor mailing list