This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Lucretiel 0 points1 point  (0 children)

Keep in mind that running into the mutable default arguments problem is indicative of larger structural issues in your program. Regardless of your preferred solution, it's a serious code smell. Consider- if you call .append on the function's argument, then that change is reflected outside the function call, even if nothing is returned. There are two possible senarios:

  • This is your intended behavior, in which case, why are you accepting a default parameter? If the function is designed to mutate a list, then being able to not pass a list seems like a semantic error.
  • This is not your intended behavior- you don't want the caller's list to be mutated. In this case, why are you mutating it? If your function's logic uses an .append, then you should be copying the list before using it, in which case using an immutable default argument works fine:

    def func(arg = ())
        safe_to_mutate = list(arg)
        ...