Valentin Coudert Valentin Coudert - 22 days ago 9
Python Question

Global variable with imports between 3 files

I come from this thread that was helpful but not enough. My case is slightly different but most important is my situation: I'm refactoring a code of 1000+ lines (in one file) and so making a change in the name of something can quite quickly become painful.

So I've split my file into 3:


  • settings.py in which I've defined all the global variables (there are
    a lot - mostly booleans and strings)

  • synchro.py which can change
    their values

  • groups.py which can also change them



I'll simplify the stuff here.

settings.py:

MY_VAR = "plane"


synchro.py:

from settings import *
import groups

def main():
global MY_VAR
MY_VAR = "boat"
groups.update()


groups.py:

from settings import *

def update():
print MY_VAR # will print "plane" instead of "boat"


I also tried to write
import settings
instead of
from settings import *
but in that case python tells me
global settings.MY_VAR
is an error, and it does not recognize
settings.MY_VAR
if I remove the
global
line.

So what can be the quickest/easiest way to get this work?

Thanks for your help

Answer

you should do like below, its not so recommend to do from settings import * , it cause namespace pollution and make things harder to debug later. i usually only use global within the same file though i try to minimize the global usage if possible

settings.py

MY_VAR = "plane"

synchro.py:

import settings
import groups

def main():
  # no need to declare global here, access trough settings namespace instead
  settings.MY_VAR = "boat"
  groups.update()

groups.py:

import settings

def update():
  print settings.MY_VAR # will print "plane" at first, after synchro main, MY_VAR should carry 'boat'