Question

I'm supposed to work with some messy code that I haven't written myself, and amidst the mess I found out two scripts that communicate by this strange fashion (via a 3rd middleman script):

message.py, the 'middleman' script:

class m():
    pass

sender.py, who wants to send some info to the receiver:

from message import m

someCalculationResult = 1 + 2
m.result = someCalculationResult

receiver.py, who wants to print some results produced by sender.py:

from message import m

mInstance = m()
print mInstance.result

And, by magic, in the interpreter, importing sender.py then receiver.py does indeed print 3...

Now, what the hell is happening behind the scenes here? Are we storing our results into the class definition itself and recovering them via a particular instance? If so, why can't we recover the results from the definition itself also? Is there a more elegant way to pass stuff inbetween scripts ran sucessively in the interpreter?

Using Python 2.6.6

Was it helpful?

Solution

That is just a convoluted way to set a global.

m is a class, m.result a class attribute. Both the sender and receiver can access it directly, just as they can access m.

They could have done this too:

# sender
import message
message.result = someCalculationResult

# receiver
import message
print message.result

Here result is just a name in the message module top-level module.

It should be noted that what you are doing is not running separate scripts; you are importing modules into the same interpreter. If you ran python sender.py first, without ever importing reciever.py, then separately running python receiver.py without ever importing sender.py this whole scheme doesn't work.

There are myriad ways to pass data from one section of code to another section, too many to name here, all fitting for a different scenario and need. Threading, separate processes, separate computers all introduce different constraints on how message passing can and should take place, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top