How to use Python Decorator to change only one part of function? -


i practically repeating same code 1 minor change in each function, essential change.

i have 4 functions similar this:

def list_expenses(self):     explist = [(key,item.amount) key, item in self.expensedict.iteritems()] #create list dictionary, making tuple of dictkey , object values     sortedlist = reversed(sorted(explist, key = lambda (k,a): (a))) #sort list based on value of amount in tuples of sorted list. reverse high low     ka in sortedlist:           k, = ka           print k ,  def list_income(self):     inclist = [(key,item.amount) key, item in self.incomedict.iteritems()] #create list dictionary, making tuple of dictkey , object values     sortedlist = reversed(sorted(inclist, key = lambda (k,a): (a))) #sort list based on value of amount in tuples of sorted list. reverse high low     ka in sortedlist:         k, = ka         print k ,   

i believe refer violating "dry", don't have idea how can change more drylike, have 2 seperate dictionaries(expensedict , incomedict) need work with.

i did google searching , found called decorators, , have basic understanding of how work, no clue how apply this.

so request/question:

  1. is candidate decorator, , if decorator necessary, hint decorator should do?

  2. pseudocode fine. don't mind struggling. need start with.

what think using separate function (as private method) list processing? example, may following:

def __list_processing(self, list):      #do generic processing of lists  def list_expenses(self):     #invoke __list_processing self.expensedict parameter  def list_income(self):     #invoke __list_processing self.incomedict parameter 

it looks better since complicated processing in single place, list_expenses , list_income etc corresponding wrapper functions.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

qt - How to embed QML toolbar and menubar into QMainWindow -