How do I find out if the variable is declared in Python?
Posted
by golergka
on Stack Overflow
See other posts from Stack Overflow
or by golergka
Published on 2010-04-09T11:40:15Z
Indexed on
2010/04/09
11:43 UTC
Read the original article
Hit count: 306
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 :)
© Stack Overflow or respective owner