Last active
December 17, 2015 17:19
-
-
Save tswicegood/5644776 to your computer and use it in GitHub Desktop.
Example of how lambdas can generally be refactored into something more readable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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')) |
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
Hmm... guess I should do something with those kwargs, huh? :-)