Accessing global variables from inside a module
Question: I wrote some python code to control a number of USB (electrical relays and
temperature sensors) and RS232 (vacuum gauges) devices. From within this main
script (e.g., `myscript.py`), I would like to import a module (e.g.,
`exp_protocols.py`) where I define different experimental protocols, i.e. a
series of instructions to open or close relays, read temperature and pressure
values, with some simple flow control thrown in (e.g. "wait until temperature
exceeds 200 degrees C").

My initial attempt looked like this:

    
    
    switch_A = Relay('A')
    switch_B = Relay('B')
    gauge_1 = Gauge('1')
    
    global switch_A
    global switch_B
    global gauge_1
    
    from exp_protocols import my_protocol
    my_protocol()
    

with `exp_protocols.py` looking like this:

    
    
    def my_protocol():
        print 'Pressure is %.3f mbar.' % gauge_1.value
        switch_A.close()
        switch_B.open()
    

This outputs a global variable error, because `exp_protocols.my_protocol`
cannot access the objects defined in `myscript.py`.

It seems, from reading the answers to earlier questions here, that I could
(should?) create all my `Relay` and `Gauge` variable in another module, e.g.,
`myconfig.py`, and then `import myconfig` both in `myscript.py` and
`exp_protocols`? But if I do that, won't my `Relay` and `Gauge` objects be
created twice (thus trying to open serial ports already active, etc.)?

What would be the best (most Pythonic) way to achieve this kind of inter-
module communication?

Thanks in advance.


Answer: No matter how many times you `import myconfig`, python only imports the module
once. After the first import, future import statements just grab another
reference to the module.

Globals should only be used if these are static bits of data. Your function
would be more generic if it took the variables as parameters:

    
    
    def my_protocol(switch_A, switch_B, gauge_1):
        print 'Pressure is %.3f mbar.' % gauge_1.value
        switch_A.close()
        switch_B.open()
    

modules could use it with many combinations of data. Suppose you have blocks
of switches in a list (and I'm just making this up because I have no idea how
you configure your data...), you could process them all with the same
function:

    
    
    import exp_protocols
    
    switch_blocks = [
        [Relay('1-A'), Relay('1-B'), Gauge('1-1')],
        [Relay('2-A'), Relay('2-B'), Gauge('2-1')],
    ]
    
    for switch1, switch2, gauge in switch_blocks:    
        exp_protocols.my_protocol(switch1, switch2, gauge)
    

