Skip to content

Instantly share code, notes, and snippets.

@calvinchengx
Forked from geeknam/pyrefactors.py
Created November 14, 2012 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvinchengx/4069996 to your computer and use it in GitHub Desktop.
Save calvinchengx/4069996 to your computer and use it in GitHub Desktop.
Python refactors
"""
Use setattr
"""
# Normal
item.price = self.request['price']
item.quantity = self.request['quantity']
item.shipping = self.request['shipping']
item.save()
# Pythonic
item_attrs = ['price', 'quantity', 'shipping']
for attr in item_attrs:
setattr(item, attr, self.request[attr])
item.save()
"""
Use reduce() or list comprehension for incrementing values
"""
# Normal
total_price = 0
for item in items:
total_price += item.price * item.quantity
# Pythonic
total_price = reduce(lambda x, y: x + y.price * y.quantity, items, 0)
total_price = sum([item.price * item.quantity for item in items])
"""
Use defaultdict() to avoid initializing dictionaries
"""
# Normal
stats = {}
for line in order_lines:
if line.product_id in stats:
stats[line.product.id]['quantity'] += line.product.quantity
stats[line.product.id]['price'] += line.product.price
stats[line.product.id]['shipping'] += line.product.shipping
else:
stats[line.product.id]['quantity'] = 0
stats[line.product.id]['price'] = 0
stats[line.product.id]['shipping'] = 0
# Pythonic
from collections import defaultdict
stats = defaultdict(lambda: defaultdict(int))
item_attrs = ['price', 'quantity', 'shipping']
for line in order_lines:
for attr in item_attrs:
stats[line.product.id][attr] += getattr(line.product, attr)
"""
Use operator module with reduce()
"""
# Normal
search_keyword = 'iPhone'
Product.objects.filter(
Q(title__icontains=search_keyword) | Q(description__icontains=search_keyword) | Q(short_title__icontains=search_keyword)
)
# Pythonic
import operator
keys = ['title__icontains', 'description__icontains', 'short_title__icontains']
conditions = [(k, search_keyword) for k in keys]
Product.objects.filter(reduce(operator.or_, [Q(c) for c in conditions]))
"""
Reorganize key-value data pairs
"""
date_dict = {'2003-06-24': 2,
'2003-08-13': 1,
'2003-08-19': 2,
'2003-08-22': 1,
'2003-08-24': 5}
# Normal
reorganized_date_dict = {'date': date_dict.keys(), 'observations': date_dict.values()}
>>> reorganized_date_dict
{'datetime': ['2003-08-13',
'2003-08-19',
'2003-06-24',
'2003-08-24',
'2003-08-22'],
'observations': [1, 2, 2, 5, 1]}
# Using the built-in zip and sorted
dates, observations = zip(*sorted(date_dict.items()))
reorganized_date_dict = {'date': dates, 'observations': observations}
>>> reorganized_date_dict
{'date': ('2003-06-24',
'2003-08-13',
'2003-08-19',
'2003-08-22',
'2003-08-24'),
'observations': (2, 1, 2, 1, 5)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment