Mutable defaults

Peter Otten __peter__ at web.de
Tue Feb 9 10:47:04 EST 2021


On 09/02/2021 16:17, Antoon Pardon wrote:

> Most of us know of the perils of mutable default values. So I came up 
> with the following proof of concept:

[...]

  def copy_defaults(f):

Once you know you need that decorator you won't need it anymore ;)

> @copy_defaults
> def prepare(value, lst = []):
>      for vl in range(value):
>          lst.append(vl)
>      return lst
> 
> print(prepare(2))
> print(prepare(3))
> 
> Running the above will produce:
> 
> [0, 1]
> [0, 1, 2]


Because of

@copy_defaults
def prepare(value, lst=[[]]):
     for vl in range(value):
         lst[0].append(vl)
     return lst

you may consider changing it to deepcopy_defaults.



More information about the Python-list mailing list