Skip to content

Instantly share code, notes, and snippets.

@tswicegood
Last active December 17, 2015 17:19
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 tswicegood/5644776 to your computer and use it in GitHub Desktop.
Save tswicegood/5644776 to your computer and use it in GitHub Desktop.
Example of how lambdas can generally be refactored into something more readable.
# using lambdas
def signed_in_both_chambers(self, **kwargs):
signed = lambda a: 'Signed in the %s' % a
return (self.filter(models.Q(bill_type='SB') | models.Q(bill_type='HB'))
.filter(actions__description=signed('House'))
.filter(actions__description=signed('Senate')))
# refactored into these methods
def has_action(self, action):
"""Filter QuerySet by a given action"""
return self.filter(actions__description=action)
def bills_from_both_chambers(self):
"""Return all House and Senate bills"""
return self.filter(models.Q(bill_type='SB') | models.Q(bill_type='HB'))
def signed_in_chamber(self, chamber):
"""Filter for bills that have been signed in a given chamber"""
action = 'Signed in the %s' % chamber.title()
return self.has_action(action)
def signed_in_both_chambers(self):
"""Return all bills that have passed both chambers"""
return (self.bills_from_both_chambers()
.signed_in_chamber('House')
.signed_in_chamber('Senate'))
@tswicegood
Copy link
Author

Hmm... guess I should do something with those kwargs, huh? :-)

@tswicegood
Copy link
Author

I just added has_action after adding another couple of methods that do that same actions__description=foo code. The original refactor was just bills_from_both_chambers and a simple version of signed_in_chamber. The benefit of the refactoring is that now I can pull just bills or bills signed in a given chamber. The original method has everything locked up in one method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment