python - Pass by value or by reference
<p>I have an object with an attribute that is a list. For example:</p>

<pre><code>obj.a = [3, 4, 5]
</code></pre>

<p>I would like to get the following behavior (but I can't manage to find a solution using magics/etc.) :</p>

<pre><code>l = obj.a
obj.a[0] = 2

print(l) --&gt; [3, 4, 5]
print(obj.a) ---&gt; [2, 4, 5]
</code></pre>

<p>Of course I could simply use copy.deepcopy : </p>

<pre><code>l = copy.deepcopy(obj.a) 
</code></pre>

<p>but for several reasons I would like, somehow, to make this step automatic/hide it for my users. </p>

<p>[EDIT]
Using <strong>getattribute</strong> and returning a copy won't work of course:</p>

<pre><code>import copy
class Test:
    def __init__(self):
         self.a = []

    def __getattribute__(self, attr):
        if attr == 'a':
            return copy.deepcopy(super(Test, self).__getattribute__(attr))
</code></pre>

<p>Any help appreciated !</p>

<p>Thnak you,
Thomas </p>

<p>It's not possible to make the assignment <code>l = obj.a</code> make a copy of <code>obj.a</code>.  As deceze said in a comment, you could make <code>a</code> a property that returns a copy of the value every time you access it, but that would, well, make a copy every time you access it, not just when you assign it to <code>l</code>.  That's going to be inefficient, and probably not the behavior you want anyway</p>

<p>There's no way for <code>obj</code> or <code>obj.a</code> to tell the difference between something like this:</p>

<pre><code>x = obj.a
</code></pre>

<p>and this:</p>

<pre><code>obj.a[:2]
</code></pre>

<p>Whatever happens when you access <code>obj.a</code>, it's going to happen in both cases.  You can't "look ahead" to see whether it's going to be assigned to a variable, just to copy it in that particular case.</p>

python reference