python .. this took me some time to figure out

Posted on
Tue Mar 03, 2020 1:15 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

python .. this took me some time to figure out

Code: Select all
abc=[]
def={"a":1,"b":2}
abc.append(def)
def["a"] = 99
abc.append(def)

i wanted it to be:
Code: Select all
[{"a":1,"b":2},{"a":99,"b":2}]

but it was
Code: Select all
[{"a":99,"b":2},{"a":99"b":2}]

The append function appends a pointer not a copy. ... and overwriting the pointer contents overwrites the list :shock: :oops:

Karl

Posted on
Wed Mar 04, 2020 2:04 pm
RogueProeliator offline
User avatar
Posts: 2501
Joined: Nov 13, 2012
Location: Baton Rouge, LA

Re: python .. this took me some time to figure out

Python is acting in a pretty standard way there -- I can't think of any programming language off hand that would do a deep copy of an object when doing list or dictionary operations. Of course, that doesn't typically apply to primitives - those are usually passed by value.

You can find some fairly standard deep copy routines to make copies of "normal" objects. Another hack is to serialize it to a string and then deserialize -- that will result in a new copy.

Adam

Posted on
Wed Mar 04, 2020 3:29 pm
jay (support) offline
Site Admin
User avatar
Posts: 18200
Joined: Mar 19, 2008
Location: Austin, Texas

Re: python .. this took me some time to figure out


Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Posted on
Wed Mar 04, 2020 7:10 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: python .. this took me some time to figure out

Yes, I am using copy.copy()

But, I just believed that append would include a copy of the dict.

And in hindsight it is clear.

Karl


Sent from my iPhone using Tapatalk

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 4 guests