It seems that python does not delete associated objects when a variable is reassigned. Have a look at the following code:
from dataclasses import dataclass
@dataclass
class Transaction(object):
amount : int
new_balance : int
description : str
class Account(object):
def __init__(self, acc_name, balance, transactions = []):
self._acc_name = acc_name
self._balance = balance
self._transactions = transactions # list of Transaction objects
def add_income(self, amount, description = "income"):
self._balance += amount
self.transactions.append(Transaction(
amount=amount,
new_balance=self._balance,
description=description
))
@property
def transactions(self):
return self._transactions
acc = Account("User",100)
acc.add_income(100)
print(acc.transactions)
acc = None
acc = Account("User",100)
print(acc.transactions)
The output is
[Transaction(amount=100, new_balance=200, description='income')]
[Transaction(amount=100, new_balance=200, description='income')]
So we can see even though I reassigned the variable the Transaction object is still alive. In encountered this behavior, when I wanted to create a fresh instance for my tests in the setUp method from unittest. Why is it like this? Is there a possibility to delete the "child" object when the "parent" object is deleted? What is the best practice in this situation?