0

I have a weird process in my python code (3.7, flask). I use this code

def add_charge(id):
   move = get_move(id)
   charge = get_charge(move)

def get_charge(move: dict, charge: dict = {}) -> dict:
   charge = adapt_charge(move, charge)
   return charge

I adapt my code to simplify it. the function get_charge will add a price on a move depending on move data and also the current charge. In the first function, I call get_charge without specify a charge value, so by default, charge will be equal to {}. The first time I use it, it works well but then, it seems to keep in memory the last value of charge. It's like when I affect a new value to charge, the default value evolve.

I solved it by using a deepcopy before charge assignment. But it's a weird process, I don't find anything on python or flask docs which explain that. If someone have an answer, I prefer to not use a deepcopy

  • 2
    Use `None` as the default value, then set `charge = {}` in the body of the function if the argument value is `None`. – chepner Jun 20 '22 at 14:37
  • 1
    The default values are evaluated at *definition time*, so the `dict` (which is mutable) is created when the function is defined. Then on the first call it is empty, on the second call it contains the values of the first call, see also: https://florimond.dev/en/posts/2018/08/python-mutable-defaults-are-the-source-of-all-evil/ – Jan Christoph Terasa Jun 20 '22 at 14:43

0 Answers0