Reputation: 503
I'm writing some string representations for the data in a django model and my code gets quite repetitive. What would be the best way to stay out of the rain?
Here is two of the methods:
def get_known_citys_string(user):
entrys = HTTPRequestData.objects.filter(user=user)
counter = Counter()
for entry in entrys:
counter[entry.city] += 1
return counter_to_string(counter)
def get_known_devices_string(user):
entrys = HTTPRequestData.objects.filter(user=user)
counter = Counter()
for entry in entrys:
counter[entry.device] += 1
return counter_to_string(counter)
Upvotes: 2
Views: 107
Reputation: 68077
Another alternative is to use functools.partial, for that succinct functional flavour:
from functools import partial
def getter(attrname, user):
entrys = HTTPRequestData.objects.filter(user=user)
counter = Counter()
for entry in entrys:
counter[getattr(entry, attrname)] += 1
return counter_to_string(counter)
# Define functions as variations on getter
get_known_citys_string = partial(getter, 'city')
get_known_devices_string = partial(getter, 'device')
Upvotes: 1
Reputation: 385900
There are many ways to approach this. Here's one:
def get_known_fields_string(user, fieldSelector):
entrys = HTTPRequestData.objects.filter(user=user)
counter = Counter()
for entry in entrys:
counter[fieldSelector(entry)] += 1
return counter_to_string(counter)
def get_known_citys_string(user):
return get_known_fields_string(user, lambda entry: entry.city)
def get_known_devices_string(user):
return get_known_fields_string(user, lambda entry: entry.device)
Upvotes: 3
Reputation: 56527
That's why functions were invented...
def common(user, field):
entrys = HTTPRequestData.objects.filter(user=user)
counter = Counter()
for entry in entrys:
counter[getattr(entry, field)] += 1
return counter_to_string(counter)
def get_known_citys_string(user):
return common(user, "city")
def get_known_devices_string(user):
return common(user, "device")
Upvotes: 2