a little python learning

User avatar
kw123
Posts: 8705
Joined: Sun May 12, 2013 4:44 pm
Location: Dallas, TX
Contact:

a little python learning

Post by kw123 »

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
ryanbuckner
Posts: 1409
Joined: Sat Oct 08, 2011 12:33 pm
Location: Northern Virginia
Contact:

Re: a little python learning

Post by ryanbuckner »

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
User avatar
kw123
Posts: 8705
Joined: Sun May 12, 2013 4:44 pm
Location: Dallas, TX
Contact:

Re: a little python learning

Post by kw123 »

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
User avatar
jay (support)
Site Admin
Posts: 19232
Joined: Wed Mar 19, 2008 11:52 am
Location: Austin, Texas
Contact:

Re: a little python learning

Post by jay (support) »

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
Post Reply

Return to “Karl's Plugins and Scripts”