How to use variables across modules

Mark Lawrence breamoreboy at
Sat Nov 2 23:32:00 CET 2013

On 02/11/2013 21:33, juel4700 at wrote:
> Im a newbee at python, and im trying to figure out how to use variables and setups across modules.
> Am I right when i think its smart to keep seperate functions of a program in seperate modules?

If your code base gets too large to handle in one module sure.  If it's 
only a few hundred lines of code why bother?

> I have a main program module called and in that i have this:
>      # Sets GPIO's to HIGH = Relays OFF
>      try:
>          import RPi.GPIO as GPIO
>      except RuntimeError:
>          Print("Error importing RPi.GPIO!!")

You catch the wrong error, it should be ImportError.  Correct this and 
you print a pretty message and continue so...

>      GPIO.setmode(GPIO.BOARD)'ll get a traceback here as your code knows nothing about GPIO 
because of the ImportError that you've so carefully mishandled.  Don't 
worry about it, we've all done it at one time or another :)

>      GPIO.setwarnings(False)
>      # GPIO16 is relay1
>      GPIO.setup(16, GPIO.OUT, initial=GPIO.HIGH)
>      # GPIO11 is relay2
>      GPIO.setup(11, GPIO.OUT, initial=GPIO.HIGH)
> I then import a module (in that module1 i have a function called Relay) and try to use the function with module1.Relay(1,1)
> But the function in module1 needs the GPIO from the to Work. How do I go about with this? I really dont want the GPIO setting part in the module1, I dont want it to be run everytime I run the module1.Relay(1,1) call..

Keeping everything in one module is actually the simplest approach.  If 
you want to keep separate modules repeat the GPIO import as needed.  The 
thing to beware of is circular imports if you have many modules.

> What is best practice for working across modules. (im making a controller for my house' heat system, so it would be nice, if I can do this the right way, the first time.)
> Im and experienced vbs and php coder, but a real newbe when it comes to python ;)
> I Really hope you Guys will lead me in the right direction..
> Kind regards Juel

Finally if you're using google groups would you be kind enough to read, 
digest and action this

Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

More information about the Python-list mailing list