I am using python 3. and would like to know if the message data attached to a pypubsub Sendmessage command is sent by reference or by value? It appears to be sent by reference but I was wondering if someone could verify that.
Also the documentation says "Message Immutability: message contents must be left unchanged by listeners, but PyPubSub does not verify this"
The code example below suggests that references to the message-data arguments are being sent and that modifying those data modify the original data (not a passed copy of the data) . Is there a reason why modifying the message data in the listener routine is a bad idea?
from pubsub import pub
class widget():
def __init__(self):
self.thingy = [{'biz':0},{'baz':1},{'buz':2}]
pub.subscribe(self.listen_for, 'wodget')
def listen_for(self, arg1):
print('wodget heard')
print(self.thingy)
print(arg1)
def send_thingy(self):
arg1 = self.thingy
pub.sendMessage('widget',arg1=arg1)
class wodget():
def __init__(self):
self.thongy = None
pub.subscribe(self.listen_for, 'widget')
# listen calendar
def listen_for(self, arg1):
print('widget heard')
print(arg1)
self.thongy = arg1
self.thongy[1]['baz']=99
print(arg1)
print(self.thongy)
arg1 = self.thongy
pub.sendMessage('wodget',arg1=arg1)
if __name__ == "__main__":
aWidget = widget()
aWidget.send_thingy()
aWodget = wodget()
aWidget.send_thingy()
A simple script seems to suggest the behavior of modifying objects using pypubsub callbacks is consistent with normal python behavior which makes sense to me, as pypubsub is just function callbacks. See below.
Also see: How do I pass a variable by reference? for a discussion of immutability.
OUTPUT: