views:

130

answers:

2

I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff):

main.py

import singleton
import printer

def main():
   singleton.Init(1,2)
   printer.Print()

if __name__ == '__main__':
   pass

singleton.py

variable1 = ''
variable2 = ''

def Init(var1, var2)
   variable1 = var1
   variable2 = var2

printer.py

import singleton

def Print()
   print singleton.variable1
   print singleton.variable2

I expect to get output 1/2, but instead get empty space. I understand that after I imported singleton to the print.py module the variables got initialized again.

So I think that I must check if they were intialized before in singleton.py:

if not (variable1):
   variable1 = ''
if not (variable2)
   variable2 = ''

But I don't know how to do that. Or there is a better way to use singleton modules in python that I'm not aware of :)

+7  A: 

The assignment inside Init is forcing the variables to be treated as locals. Use the global keyword to fix this:

variable1 = ''
variable2 = ''

def Init(var1, var2)
   global variable1, variable2
   variable1 = var1
   variable2 = var2
Marcelo Cantos
Thanks a lot! That was exactly what I was looking for.
+1  A: 

You can use de dictionaries vars and globals:

vars().has_key('variable1')

or

globals().has_key('variable1')

Edit:

Also...

'variable1' in vars()

e.g.

if not 'variable1' in vars():
  variable1 = ''
Alfred