Pull Last 3 Months

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Oct 18 02:33:58 CEST 2007


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()
    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.

-- 
 \      "I hope some animal never bores a hole in my head and lays its |
  `\   eggs in my brain, because later you might think you're having a |
_o__)          good idea but it's just eggs hatching."  -- Jack Handey |
Ben Finney



More information about the Python-list mailing list