0

Lets say i have this function:

def test(t=[]):
    t.append(1)
    print(t)

if i run it a few times the list will be appended like this:

test() #[1]
test() #[1, 1]

so where is this list stored? it is not in globals() // locals() the functions __dict__ is also empty

Alex
  • 111
  • 2
  • 9
  • 2
    Related: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – DeepSpace Jul 09 '22 at 00:12

2 Answers2

2

Okay found it:

It is stored in __defaults__

here you can even set it to a different tuple

Alex
  • 111
  • 2
  • 9
  • *"you can even set it to a different tuple"* For the sanity of *everyone* that will ever need to maintain that code: please DON'T – DeepSpace Jul 09 '22 at 00:12
  • 1
    @DeepSpace yes im just learning about some inner structures of python. wont use this. – Alex Jul 09 '22 at 00:18
-2

This is because the python interpreter/compiler assigns the default value to the argument at compile time.

That's why default arguments should be immutable.

def test(t=None):
    if t is None:
      t = []
    t.append(1)
    print(t)
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • 1
    This is not really what OP is asking. Otherwise, there is [a canonical duplicate](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). – DeepSpace Jul 09 '22 at 00:13