a little python learning

Posted on
Tue Sep 19, 2023 4:40 pm
kw123 offline
User avatar
Posts: 8366
Joined: May 12, 2013
Location: Dallas, TX

a little python learning

Code: Select all
def xxx(data):
   ## has a thread method  with a queue  that gets data that does
   time.sleep(1)
   print "{}".format(data)

data={"abc":"123"}
xxx(data)
data["def"] = "fgh"

will print: {"abc":"123", "def":"fgh"}

xxx gets a pointer to data, then the main program overwrites data, since xxx has a delay of 1 sec xxx will print the additional item "def"

:o

Karl

Posted on
Wed Sep 20, 2023 10:11 am
ryanbuckner offline
Posts: 1080
Joined: Oct 08, 2011
Location: Northern Virginia

Re: a little python learning

Code: Select all
/usr/local/bin/python3.10 /Users/ryanbuckner/Library/Application Support/JetBrains/PyCharmCE2023.1/scratches/scratch_3.py
{'abc': '123'}

Process finished with exit code 0

Posted on
Fri Sep 22, 2023 4:03 am
kw123 offline
User avatar
Posts: 8366
Joined: May 12, 2013
Location: Dallas, TX

Re: a little python learning

If it is a linear execution it works fine . Ie when xxx is finished before the main program resumes

But when xxx has an internal thread that runs independent of the main pgm and has a delay then it happens

In my real application xxx is feeding a queue that a thread reads very 0.5 secs and then sends an http message with the dict. There the additional item appeared as the main pgm adds an item to the dict immediately and writes it to a file for further local processing.

The underlying issue is that xxx gets a pointer to the dict not a copy.

So I am now always using xxx( copy.deepcopy(thedict) )


Sent from my iPhone using Tapatalk

Posted on
Fri Sep 22, 2023 10:51 am
jay (support) offline
Site Admin
User avatar
Posts: 18224
Joined: Mar 19, 2008
Location: Austin, Texas

Re: a little python learning

Python is a pass-by-reference language (as opposed to pass by value). Passing an object around across threads can be tricky in any language and is what you noticed.

Technically, it's pass references to objects by value, but pass by reference is the closer model.

Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 10 guests