python - Pass by value or by reference -


i have object attribute list. example:

obj.a = [3, 4, 5] 

i following behavior (but can't manage find solution using magics/etc.) :

l = obj.a obj.a[0] = 2  print(l) --> [3, 4, 5] print(obj.a) ---> [2, 4, 5] 

of course use copy.deepcopy :

l = copy.deepcopy(obj.a)  

but several reasons like, somehow, make step automatic/hide users.

[edit] using getattribute , returning copy won't work of course:

import copy class test:     def __init__(self):          self.a = []      def __getattribute__(self, attr):         if attr == 'a':             return copy.deepcopy(super(test, self).__getattribute__(attr)) 

any appreciated !

thnak you, thomas

it's not possible make assignment l = obj.a make copy of obj.a. deceze said in comment, make a property returns copy of value every time access it, would, well, make copy every time access it, not when assign l. that's going inefficient, , not behavior want anyway

there's no way obj or obj.a tell difference between this:

x = obj.a 

and this:

obj.a[:2] 

whatever happens when access obj.a, it's going happen in both cases. can't "look ahead" see whether it's going assigned variable, copy in particular case.


Comments