0

I want to create a python 3 program consisting of a main python program and several modules, I will import into the main program. I want use variables created in the main program and use them in the modules. Momentarily I have this in my main program:

   import sys
   sys.dont_write_bytecode = True
   import importlib

   from tests import blather

   relayrange = 87
   relay = [0] * relayrange

   blather.BLA(relayrange, relay)

In the same map as my main function I have a directory "tests" with in it the python file blather.py, it contains this code

def BLA(relayrange, relay):
print ('this is module BLA')
print (relayrange)
print (relay)

This works! But as you can see I needed to retort to passing the variables to the function, because I found no other way to simply use variables from the main program (which I am told are automatically "global") in the module BLA.

So my question is, how can I use the (global?) variables from the main body of the python code in an imported module? I may have many dozens of variables in my main file, that I want to use in my module(s), so parameter passing like this will become very unwieldy.

I tried different test with using the keyword global, but nothing worked. As you probably can tell I'm new to Python.

P.S. after being marked as duplicate, I finally solved this problem by putting all global variables in a module g.pi, and importing g.pi in each module that needed global variables, so now i have three, not two modules, namely main.pi, blather.pi, and g.py

main.pi contains:

import sys
#sys.dont_write_bytecode = True
import importlib

from shared import g
from tests import blather

print(g.relayrange)
print(g.relay)

g.relay[47] = 10
print (g.relay)
g.relay[12] = 999
blather.BLA()

and blather.py contains:

from shared import g

def BLA():
    print ('in module')
    print (g.relay)

g.py just contains the variables, like so:

relayrange = 87
relay = [0] * relayrange
mahjongg
  • 19
  • 4
  • As explained in one of the answers in the 'duplicated question', I'd go with a new module `import module_variables as mv` and then use them as `mv.variable_one` or somethign like that. I guess you could also use `from module_avriables import *` – tglaria Dec 24 '15 at 15:09
  • Well, after some pondering and research I found I could place the variables I wanted to be global for all modules in -another- module I called g.phy then used these "globalized" variables by importing g.py and using the notation g.relayrange and g.relay, both in the main module, and in any imported module. – mahjongg Dec 24 '15 at 15:22

0 Answers0