views:

198

answers:

3

I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:

def copyright_dates(start_year = Date.today().year)
    [start_year, Date.today().year].sort.uniq.join(" - ")
end

I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. The same method in Python looks like:

def copyright_dates(start_year = datetime.datetime.today().year):
    years = list(set([start_year, datetime.datetime.today().year]))
    years.sort()
    return " - ".join(map(str, years))

It's been years since I've touched Python, so I'm betting there's an easier way to do it. Any ideas?

EDIT: I know lists and sets are a bit of overkill, but I want the following output assuming the code is run in 2009:

copyright_dates()     # '2009'
copyright_dates(2007) # '2007 - 2009'
copyright_dates(2012) # '2009 - 2012'
+5  A: 
from datetime import datetime

def copyright_dates(start_year = datetime.now().year):
    return " - ".join(str(y) for y in sorted(set([start_year, datetime.now().year])))
John Kugelman
Nice. Thanks for the quick response.
Chris Doggett
I was able to get it down to " - ".join(map(str, sorted(set([start_year, datetime.now().year])))) if I left out the list comprehension.
Chris Doggett
+2  A: 

Lists and sets seem to be overkill to me.

How about this:

def copyright_dates(start=datetime.datetime.today().year):
    now = datetime.datetime.today().year
    return (start==now and str(now) or "%d - %d" % (min(start, now), max(start, now)))
cfrantz
Also nice, only thing missing is the sort, if for some reason I decided to pass in a future date. That's the only reason I use the lists and sets. I'll update the question with the expected output.
Chris Doggett
No need for sort when you're dealing with only two items. The order issue is fixed now, I believe.
ΤΖΩΤΖΙΟΥ
+4  A: 

Watch out for the default parameter which is evaluated once. So if your web application runs over 12/31/09 without a restart, you won't get the expected output.

Try:

def copy(start=None):
    start, curr = start if start else datetime.today().year, datetime.today().year
    return str(start) if start == curr else '%d - %d' % tuple(sorted([start, curr]))
ars