Hacker News new | ask | show | jobs
by Jtsummers 1063 days ago
Just as a demo of what you're saying:

If you were to do (the following is from memory, probably has typos):

  def func(arr=[]):
    print(locals)
You'd see `arr` there. The `[]` value lives in `func.__defaults__`:

  def func(arr=[]):
    print(locals)
    print(func.__defaults__) # will print: ([],)
If you assign to `arr` nothing changes with defaults:

  def func(arr=[]):
    print(locals)
    arr = 10
    print(func.__defaults__) # will still print: ([],)
But since lists are mutable, calling a mutating function on the list referenced by `arr` will cause a mutation of the list stored in defaults:

  def func(arr=[]):
    print(locals)
    arr.append(10)
    print(func.__defaults__) # will print: ([10],)
But only when `func` is called without something to assign to `arr`:

  # if pristine and it has not been run before
  def func(arr=[]):
    print(locals)
    arr.append(10)
    print(func.__defaults__) # will print: ([],)
  func([])