Reference python object in an imported function
<p>I have two .py script files. The "main" script will import the second script containing misc "helper" functions.</p>

<p>In the main script, I have set up an object for a SPI interface. I would like to write functions in the imported file that use the SPI interface directly. I'm a noob at this and tried writing and passing in various ways but always get errors.</p>

<p><strong>mainscript.py</strong></p>

<pre><code>import helperfunctions.py as helper

spi = spidev.SpiDev()
spi.open(0, 0)

response = spi.xfer([ ... some data ...])  #this works when
                                           #called from mainscript.py

helper.sendOtherStuff()  #this doesn't work (see helper script below)
</code></pre>

<p><strong>helperfunctions.py</strong></p>

<pre><code>def sendOtherStuff():
   #need to somehow reference 'spi.' object from mainscript.py file 
   otherData = ([... some different data ...])
   resp = spi.xfer([otherData])  #this fails because helperfunctions
                                 #apparently doesn't know spi. object
   return resp
</code></pre>

<p>I have the same general question often regarding global variable values as well. I'm sure there is a "better" way to do it, but out of convenience for now, I often wish to define some global variables in mainscript.py then reference those globals inside functions of helperfunctions.py. I can't figure a way to do this. Going the other way is easy - declare the globals inside helperfunctions.py then reference them from mainscript.py as helper.variableName, but I don't know how to go the other direction.</p>

<p>Any direction is much appreciated. Thank you.</p>

<p>By my lights the easiest thing to do would be to pass the spi object to the helper function as a parameter:</p>

<pre><code>def sendOtherStuff(spi):
    otherData = ([... some different data ...])  
    return spi.xfer([otherData]) 
</code></pre>

<p>Once it's passed in, you can call methods on it in the body of the function. I removed your variable assignment because it seemed redundant.</p>

python object import