'How to not repeat variables inside methods?

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'}]

Ledger is created by the 2 methods withdraw and deposit that just append information into ledger each time they're called.

Obviously withdraws amount are negative and deposits amount are positive, so I wrote this function to get the balance of the class.

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

I created another function percentage_spent where I need the exact same variables of get_balance(Alldeposited, Allwithdrawn), How can I make my code less repetitive? I tried to initialize these variables at the top of the class and inside the constructor but it does not work, I thought that I could create 2 specific method to get the 2 values but at this point it's better to repeat the code. The following is the so repetitive code that I wrote.

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

Can you help me?



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BlackBeans
Solution 2 MatsLindh