Skip to content

Instantly share code, notes, and snippets.

@rctay
Forked from geeknam/pyrefactors.py
Created November 14, 2012 03:08
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 rctay/4070023 to your computer and use it in GitHub Desktop.
Save rctay/4070023 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]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment