A simple question, perhaps, but I can't quite phrase my Google query to find the answer here. I've had the habit of making copies of objects when I pass them into object constructors, like so:

...
def __init__(self, name):
    self._name = name[:]
...

However, when I ran the following test code, it appears to not be necessary, that Python is making deep copies of the object values upon object instantiation:

>>> class Candy(object):
...     def __init__(self, flavor):
...             self.flavor = flavor
...
>>> flav = "cherry"
>>> a = Candy(flav)
>>> a
<__main__.Candy object at 0x00CA4670>
>>> a.flavor
'cherry'
>>> flav += ' and grape'
>>> flav
'cherry and grape'
>>> a.flavor
'cherry'

So, what's the real story here? Thanks!

EDIT:

Thanks to @Olivier for his great answer. The following code documents a better example that Python does copy by reference:

>>> flav = ['a','b']
>>> a = Candy(flav)
>>> a.flavor
['a', 'b']
>>> flav[1] = 'c'
>>> flav
['a', 'c']
>>> a.flavor
['a', 'c']
Edit
Report