3 ms·
More concretely, one of the classic Python bugs is to use `[]` as a default argument and then mutate what "is obviously" a local variable.
by Smaug123 3y ago
More concretely, one of the classic Python bugs is to use `[]` as a default argument and then mutate what "is obviously" a local variable.
- nighthawk454 3y agoI think it's even more safe/preferable to use non-mutable `None`s as a default and do: ``` def myfunc(x=None): x = x if x is not None else [] ... ```
- memco 3y agoIn some cases you can also do: x = x or [] Your method is best when you might get falsy values but if that’s not an issue the `or` method is handy.
- aunderscored 3y agoI tend to dislike this method as it's unclear what or returns unless you already know that or behaves this way. x if x is not None else default is cleaner in my opinion
- gcanyon 3y agoI'm learning python, and I hit this milestone about a week ago!
- at_compile_time 3y agoWhat's it do?
- travisjungroth 3y agoWhen you set an object as a default that object is the default for all calls to that function/method. This also holds true if you create the object, like that empty list. So in this case, every call that uses the default argument is using the same list. def listify(item, li=[]): li.append(item) return li listify(1) # [1] listify(2) # [1, 2]