Max Yankov
Max Yankov

Reputation: 13297

How do I find out if the variable is declared in Python?

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 :)

Upvotes: 3

Views: 332

Answers (2)

Alfre2
Alfre2

Reputation: 2089

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 = ''

Upvotes: 2

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

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

Upvotes: 7

Related Questions