DEV Community

loading...

Discussion on: 5 common mistakes made by beginner Python programmers

Collapse
ingles98 profile image
Filipe Reis

Wait how is the last example true?? Lst is under the function scope only...

Collapse
rhymes profile image
rhymes

lst is evaluated when the file is interpreted, hence it's always the same thing in memory. It's one of the gotchas of Python, you can see it here:

>>> def func(a, lst=[]):
...     print(id(lst))
...
>>> func(3)
4451985672
>>> func(4)
4451985672

As you can see lst points to the same object in memory.

If you pass an argument it will substitute the one defined at evaluation time:

>>> r = []
>>> def func(a, lst=[]):
...     lst.append(a)
...     return lst
...
>>> func(1, r)
[1]
>>> func(2, r)
[1, 2]
>>> r
[1, 2]
>>> func(4)
[4]

Notice how when I don't pass an external list as an argument, it starts using the default one.

Collapse
prahladyeri profile image
Prahlad Yeri

You are right in that it shouldn't happen as per the rules of the scope (variables defined within function scope should be destroyed once they leave that scope) but still, it happens! You can call it a bug of the cpython interpreter though the chances of falling in this trap is very less. You'll have to be careless enough to accept a default parameter and not handle its value at all in the function and just let it free (which is quite rare).

Collapse
johncip profile image
jmc

The names are under function scope, but the values are stored as entries in a collection (tuple I think?) called func_defaults (__defaults__ in 3). It's attached to the function object, so I think that means it has the same scope as the declaration.

Python 🙄