Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A 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)


Again, 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.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: