From: Charles R H. <cha...@gm...> - 2006-08-26 16:22:34
|
Hi, On 8/26/06, Bill Baxter <wb...@gm...> wrote: > > You're sure it's not just pass-by-reference semantics biting you? > If you make an array and pass it to another class or function, by default > they just get a reference to the same array. > so e.g.: > > a = numpy.array ([1,2,3]) > some_class.set_array(a) > a[1] = 10 > > Then both the local 'a' and the 'a' that some_class has are now [1,10,3]. > If you don't want that sharing then you need to make an explicit copy of a > by calling a.copy (). > Watch out for lists or dicts of arrays too. The python idom for copying > a list: new_list = list_orig[:], won't copy the contents of elements that > are array. If you want to be sure to make complete copies of complex data > structures, there's the deepcopy method of the copy module. new_list = > copy.deepcopy(list_orig). > > I found a bunch of these sorts of bugs in some code I ported over from > Matlab last week. Matlab uses copy semantics for everything, > Matlab does copy on write, so it maintains a reference until an element is modified, at which point it makes a copy. I believe it does this for efficiency and memory conservation, probably the latter because it doesn't seem to have garbage collection. I could be wrong about that, though. Chuck |