def convert_to_internal(self, agenda):
x = []
t = OrderedDict(sorted(agenda['timconf'].items(),
key=TimeSerializer.__day_comparator))
for day, items in t.items():
First of all, from what I can see, you're only using t
once: in the loop.
Instead, I'd suggest writing
t = sorted(agenda['timconf'].items(), key=TimeSerializer.__day_comparator)
for day, items in t:
That gets rid of the OrderedDict
.
Let's look at the following piece of code:
for attr in ['begin', 'end']:
if hasattr('item', attr):
item[attr] = item[attr] + day_num*24*60*60
What does this do? Of course! It shifts an item by a given number of days.
But it also does some funny things. It checks if item
has an attribute (.attribute
), but then modifies the value at a key ([key]
). So item
is some weird attribute dictionary-ish thing. Let's use all that knowledge together.
def shift_time_item(time_item, num_days):
delta = num_days * 24 * 60 * 60
try:
time_item.begin += delta
except AttributeError:
pass
try:
time_item.end += delta
except AttributeError:
pass
Now, you might think it is not DRY, because I repeat a similar try/except, but it is. And it does not really matter, because the business logic is there only once: I specify how to move an item just once.
day_num = TimeSerializer.DAYS_INVERSE[day]
for item in sorted(items, key=lambda k: k['begin']):
shift_time_item(item, num_days)
x.append(TimeItem(**item))
Now, I'm left wondering what to do about the x
. Why not
items = sorted(items, key=lambda k: k.begin)
for item in items:
shift_time_item(item, num_days)
And then use items
instead of x
.
p = ';'.join(map(str, items))
return "-t {} -n {} -p '{}'".format(agenda['timeZone'], agenda['locale'], p)