Pull Last 3 Months
John Machin
sjmachin at lexicon.net
Wed Oct 17 21:40:32 EDT 2007
On 18/10/2007 10:33 AM, Ben Finney wrote:
> Paul Hankin <paul.hankin at gmail.com> writes:
>
>> import datetime
>>
>> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
>>
>> def last_months(n):
>> month = datetime.date.today().month
>> return [months[(month - i - 1) % 12] for i in range(n)]
>>
>> print last_months(3)
>
> Heck you don't even need the magic number 12 in there.
>
> import datetime
>
> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
Heck if you really want to be anal, you could even guard against a typo
(or one of those spaces actually being '\xA0' [seen it happen]) by
adding in here:
MONTHS_IN_YEAR = 12
assert len(months) == MONTHS_IN_YEAR
> def last_months(n):
> month = datetime.date.today().month
> return [months[(month - i - 1) % len(months)
> for i in range(n)]
>
> In general I try to avoid magic numbers: always be explicit about the
> semantic purpose of the number, either by binding a meaningful name to
> it and only using that reference thereafter, or showing how that value
> is derived.
>
It's a bit hard to see how anybody could imagine that in the expression
[months[(month - i - 1) % 12] for i in range(n)]
the number 12 referred to anything but the number of months in a year.
More information about the Python-list
mailing list