3 ms·
My canonical example is that you want a function to have an argument that defaults to an empty list: def func(arg=[]): arg.append(1) print(
by fragmede 2y ago
My canonical example is that you want a function to have an argument that defaults to an empty list:
def func(arg=[]):
arg.append(1)
print(arg)
func()
func()
func()
shoving a print into a function definition is weird and not something you'd do normally. But someone who doesn't know this footgun is going to write a function that defaults to an empty list, and then tear their hair out when things are broken.
- deleted 2y ago[deleted]
- MrJohz 2y agoThat's true, this is the example that most people will run into in practice. But the print example is useful because it shows what's going on more explicitly: the default argument gets evaluated as part of the function's definition. I think this helps people get a better intuition for how Python's interpreter works when it comes to evaluating function definitions.