4 ms·
I've always thought that #1 is a sign of an incorrect operation altogether. If you want to always modify the passed parameter, it doesn't make sense to have a d
by mark-r 13y ago
I've always thought that #1 is a sign of an incorrect operation altogether. If you want to always modify the passed parameter, it doesn't make sense to have a default. If you want to return a modified version of the input, you should make a copy immediately and then you don't get this problem. Doing both an in-place modification and returning a modified object at the same time is just wrong.
- ajanuary 13y agoA slightly more realistic example: class Bag(object): def __init__(self, items=[]): self.items = items def add_item(self, item): # check the item is valid self.items.append(item) bag1 = Bag() bag1.add('an item') bag2 = Bag() print(bag2.items)
- mark-r 13y agoAgain, the problem is not what it appears. You're keeping a reference to an existing item rather than making a copy. The results would be just as bad if you passed in an initial list rather than taking the default. initial = ['first item'] bag3 = Bag(initial) bag3.add_item('second item') print(initial) I think the surprising thing to most people is that you don't automatically get a copy when you do the assignment. That's how it works in older languages like C and C++, and how it appears to behave when you use immutable objects.