How to not repeat variables inside methods?

Question:

the variables self.ledger inside a class displays some deposits and withdraws in this way:

[{'amount': 50, 'description': 'Santa Claus arrived'}, {'amount': -12.5, 'description': 'Thiefs arrived'}]

The 2 methods withdraw and deposit append information into self.ledger each time they’re called.

Here is the function to get the balance:

def get_balance(self):
   self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
   self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
   self.balance = self.Alldeposited - self.Allwithdrawn
   return self.balance

Here is the function to get the percentage spent:

def percentage_spent(self):
    self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
    self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
    Percentage = round(((self.Allwithdrawn*100)/self.Alldeposited),-1)
    return Percentage

As you can see the code is repetitive, how could I make it less repetitive?

Asked By: Jock

||

Answers:

Move the common functionality to its own function, or split it into two distinct ones:

def deposited_and_withdrawn():
    return {
        'deposited': sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
        'withdrawn': abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
    }

or split it further:

def deposited():
    return sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])

def withdrawn():
    return abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))

I don’t see the need to avoid repetition inside the sum for a small code block as this (otherwise you could move the comparison out as a lambda function and then give that to a "transaction summer"-function):

def transaction_summer(transactions, filter_):
    return sum([transaction["amount"] for transaction in transactions if filter_(transaction)]

def withdrawn():
    return abs(self.transaction_summer(self.ledger, lambda x: x['amount'] < 0))

If you only need this to operate on the ledger, rename the method to ledger_summer and drop the transactions argument if it makes the code clearer to you.

Answered By: MatsLindh

There are two ways to solve this issue: either you keep track, each time you make a transaction, of the total deposited so far, and total withdrawn so far (which is the most efficient), or you simply re-calculate it each time. I would recommend going for the first solution, but since you seem to be recomputing it each time, it must not be a problem for you.

First solution: recompute it each time

Using @property, you can make something that looks like an attribute, but whose value is actually computed each time you access it (and you can’t write it). Just what we need!

class Whatever:
   [...]
   @property
   def all_deposited(self):
      return sum(transaction["amount"] for transaction in self.ledger if transaction["amount"] > 0)
   @property
   def all_withdrawn(self):
      return sum(-transaction["amount"] for transaction in self.ledger if transaction["amount"] < 0)

Second solution: keep track of withdrawn and deposited money so far

class Whatever:
   def __init__(self, ...):
      [...]
      self.all_deposited = 0
      self.all_withdrawn = 0
   [...]
   def deposit(self, amount, ...): # I don't know what the real signature is
      [...]
      self.all_deposited += amount
   def withdraw(self, amount, ...):
      [...]
      self.all_withdrawn += amount

Then, in both cases, you can access these amounts as attributes:

def percentage_spent(self):
    percentage = round(((self.all_withdrawn*100)/self.all_deposited),-1)
    return percentage

def get_balance(self):
   self.balance = self.all_deposited - self.all_withdrawn
   return self.balance
Answered By: BlackBeans
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.