开发者

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

开发者 https://www.devze.com 2022-12-26 11:05 出处:网络
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):

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消