Home > Software engineering >  where are keywodarguments stored def test(t=[]):
where are keywodarguments stored def test(t=[]):

Time:07-09

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

CodePudding user response:

Okay found it:

It is stored in __defaults__

here you can even set it to a different tuple

CodePudding user response:

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)
  • Related