How do I know if a variable is declared in Python?

I want to use the module as a singleton, mentioned in other modules. It looks something like this (this is not the code I'm working on, but I simplified it to throw away all unrelated things):

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 1/2 output, but instead I get empty space. I understand that after I imported singleton into the print.py module, the variables were initialized again.

Therefore, I think I should check if they have been indexed before in singleton.py:

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

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

+3
2

Init . global, :

variable1 = ''
variable2 = ''

def Init(var1, var2)
   global variable1, variable2
   variable1 = var1
   variable2 = var2
+7

:

vars().has_key('variable1')

globals().has_key('variable1')

Edit:

...

'variable1' in vars()

.

if not 'variable1' in vars():
  variable1 = ''
+2

Source: https://habr.com/ru/post/1740444/


All Articles