Reputation: 25
I am creating an audit log for my economy. At this point I have it sending a message to a channel anytime someone uses an economy command.
async def audit_log(ctx, bot, action, stats=None, new_bank=None, new_money=None):
audit_channel = bot.get_channel(813610020943953920)
old_stats = stats
new_stats = stats
if new_bank is not None:
new_stats['bank'] = new_bank
if new_money is not None:
new_stats['money'] = new_money
await audit_channel.send(f'{ctx.author} did {action},\nprev-bank: {old_stats["bank"]}, prev-cash: {old_stats["money"]}\nnew-bank: {new_stats["bank"]}, new-cash: {new_stats["money"]}')
Stats is a dictionary that is assigned to someone's document in the database. Two of the values are money and bank. Not every command updates bank and money, if the command updates either it passes it through. Now that I have described the code I will describe the problem. When I get the message in discord it has both the new and the old equal to the new. When I did some prints I ended up finding that it changes the old_stats inside of the if statements. It changes the money in money and bank in bank.
I've spent about 5 hours trying to figure this out any help will be greatly appreciated.
Upvotes: 2
Views: 295
Reputation: 442
The error here is that you assign both old_stats
and new_stats
to stats, and since a dictionary is mutable python makes both old_stats
and new_stats
hold the same dict, and so if you update one you update "both". To fix this you can use the copy modules copy function: copy.copy(stats)
.
This is how your code would look fixed:
# imports
import copy
# ... other code
async def audit_log(ctx, bot, action, stats=None, new_bank=None, new_money=None):
audit_channel = bot.get_channel(813610020943953920)
old_stats = copy.copy(stats)
new_stats = copy.copy(stats)
if new_bank is not None:
new_stats['bank'] = new_bank
if new_money is not None:
new_stats['money'] = new_money
await audit_channel.send(f'{ctx.author} did {action},\nprev-bank: {old_stats["bank"]}, prev-cash: {old_stats["money"]}\nnew-bank: {new_stats["bank"]}, new-cash: {new_stats["money"]}')
new_stats
to a copy of stats
and assigns old_stats
to a copy of stats
.Upvotes: 2