I'm watching a tutorial on python and it uses this example:
def add_spam(menu=[]):
menu.append("spam")
return menu
If you call add_spam()
repeatedly then the menu list increases in size. This is new to me since I am from a C# background. But OK, fair enough.
To get around this it says that you should set the menu parameter to None
but I cannot understand why that works. Here is the code they use:
def add_spam(menu=None):
if menu is None:
menu = []
menu.append('spam')
return menu
If you call it the first time though menu will be set to [], and the second time surely if it's 'remembering' the parameter as in the first example, menu will be [] at that point and therefore it will just append spam to the list as in the first example.
The video neglects any explanation other than you should use an immutable type so I cannot understand how this works.
Edit cos I still don't get it:
What I'm seeing is that the function captures the variable, so it takes menu=[] and stores that secretly somewhere, imagine a private variable called _menu, so that if you call it again it doesn't re-evaluate it just continues to use _menu and thus it grows.
In the second example, I do not understand why it isn't simply taking menu=None and storing that secretly as _menu, so _menu = None and then when you call the 2nd function, it sets _menu=[] and it continues exactly as the first example and it grows.
The fact that None is immutable doesn't seem relevant to me, as you're not doing None=[] you're doing menu=[] so menu then stops being what it was before and becomes [] and you can modify it as you like.
Unless it's some hard-coded feature that if you put None it will not do the copying behaviour then I do not understand the difference between the two.