Time constants module - standard-library fodder?

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Fri May 30 04:45:07 EDT 2003


Ben Finney wrote:
> Many programmers in many languages break the "use named constants" rule,
> but one of the most egregious examples seems to be constants for number
> of seconds in an hour, day, week, etc.
> 
> Using the numeric literal '604800' instead of 'SECS_PER_WEEK' is as bad
> as using '3.14159265' instead of 'math.pi', for all the same reasons:
> it's prone to hard-to-find typing errors, it's not obvious to anyone
> unfamiliar with the value of the constant, it gives no context as to why
> this number is being used, etc.

That's why I'm usually writing it as "60*60*24*7"
Although giving this kind of numbers their own constant sounds reasonable.

But I'm not too fond of HOURS_PER_DAY and the other 'simple' ones.
Why, it's 24, this will *never* change, *everybody* knows this,
and if your code isn't clear when you use the number 24 directly,
I think the rest of your code has a problem, and it won't improve
much when you're using the HOURS_PER_DAY constant instead.

We might as well name the following constants:
FIRST_INTEGER_AFTER_ZERO=1
NUMBER_OF_DIGITS_IN_BASE_TEN=10
FOUR_TIMES_PI=math.pi*4

I think these kind of constants are *too* obvious and only make
your code harder to read. BUT: this depends on the situation!
I always think about the readability and maintainability while writing
the code. Perhaps in some parts, these 'obvious' constants are
needed to improve the code, but usually they are not (my opinion).

> Is there a better way?  A standard module I've missed?  Any improvements
> to offer?  Should this go into the standard library, in some form?  Why
> or why not?


> SECS_PER_MINUTE = 60
> MINUTES_PER_HOUR = 60
> HOURS_PER_DAY = 24
> DAYS_PER_WEEK = 7
> MONTHS_PER_YEAR = 12
[...]
 > SECS_PER_HOUR = MINUTES_PER_HOUR * SECS_PER_MINUTE
 > SECS_PER_DAY = HOURS_PER_DAY * SECS_PER_HOUR
 > SECS_PER_WEEK = DAYS_PER_WEEK * SECS_PER_DAY

Fine. But see above.

> DAYS_PER_YEAR_AVG = 365.25
> DAYS_PER_MONTH_AVG = DAYS_PER_YEAR_AVG / MONTHS_PER_YEAR
> WEEKS_PER_YEAR_AVG = DAYS_PER_YEAR_AVG / DAYS_PER_WEEK
[...]
 > SECS_PER_MONTH_AVG = DAYS_PER_MONTH_AVG * SECS_PER_DAY
 > SECS_PER_YEAR_AVG = DAYS_PER_YEAR_AVG * SECS_PER_DAY

I'm not happy with this: it's wrong. The avg. number of days per year
is 365.242199. Second, there's also a Siderial year, 365.256366 days.
Sometimes you need the first, sometimes the other.
Perhaps you require even greater precision than 6 fractional digits.
Either remove these constants or define them exactly
(you probably meant the Julian year).

I think you're opening a can of worms here ;-)
More info at http://www.maa.mhn.de/Scholar/calendar.html

--My €0.02,
   Irmen de Jong





More information about the Python-list mailing list