Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variables and Modules (simple example help) Python

OK I am doing some threading, and I guess when I started doing threading I assumed you can't return values like a definition (its the end of the day and my brain is about to die so maybe this is incorrect and I should start going back to get rid of global variables)

Anyway I have a test program to figure out why I can't modularize my code

a file called config.py

a_variable=0

a file called test_for_sean.py

from config import *
def blah():
  global a_variable
  a_variable=14
  return 0

a file called main.py

from config import *
from test_for_sean import *
print a_variable #this prints correctly
blah()
print a_variable #this is still printing 0....

someone link me to something so I don't kill myself

like image 985
Sean Cav Avatar asked Jan 28 '26 07:01

Sean Cav


2 Answers

When you import variables from a module the names are imported into the current module's namespace, they are not shared between both modules. The global keyword does not allow you to share names between modules, it only allows you to assign to a name that is in the global scope for that module.

To actually share variables between modules you need to access the variable through its module:

a file called config.py

a_variable=0

a file called test_for_sean.py

import config
def blah():
  config.a_variable=14
  return 0

a file called main.py

import config
from test_for_sean import blah
print config.a_variable # prints 0
blah()
print config.a_variable # prints 14
like image 189
Andrew Clark Avatar answered Jan 30 '26 19:01

Andrew Clark


Try these changes,

config.py,

a_variable = 0

tfs.py (was test_for_sean),

import config

def blah():
    config.a_variable = 14
    return 0

main.py,

import tfs, config

print config.a_variable
tfs.blah()
print config.a_variable

We still import everything from config, but are 'global' variables stay in their own modules. This way we can have global variables but still let main.py define its own a_variable if it needs to.

like image 37
Brigand Avatar answered Jan 30 '26 21:01

Brigand