Hick
Hick

Reputation: 36414

How to set dynamic global variables in Python?

Let's say I've a file a.py and a has a variable var.

In file b.py, I imported, a.py and set a.var = "hello".

Then I imported a.py in c.py and tried to access a.var but I get None.

How to reflect the change in data? It is obvious that two different instances are getting called, but how do I change it?

Edit:

What I am trying to do here is create a config file which constitutes of this:

CONFIG = {
    'client_id': 'XX',
    'client_secret': 'XX',
    'redirect_uri': 'XX'
    }

auth_token = ""

auth_url = ""

access_point = ""

Now, let's say I use config.py in the script a.py and set config.access_point = "web"

So, if I import config.py in another file, I want the change to reflect and not return "".

Edit:

Text file seems like an easy way out. I can also use ConfigParser module. But isn't it a bit too much if reading form a file needs to be done in every server request?

Upvotes: 2

Views: 2189

Answers (3)

Hamoudaq
Hamoudaq

Reputation: 1498

well , i'd use an text file to set values there,

a.py :
with open("values.txt") as f:
  var = f.read()#you can set certain bytes for read 

so whenever you import it , it will initialise new value to the var according to the values in the text file , and whenever you want to change the value of var just change the value of the text file

Upvotes: 0

silvado
silvado

Reputation: 18187

As a preliminary, a second import statement, even from another module, does not re-execute code in the source file for the imported module if it has been loaded previously. Instead, importing an already existing module just gives you access to the namespace of that module.

Thus, if you dynamically change variables in your module a, even from code in another module, other modules should in fact see the changed variables.

Consider this test example:

testa.py:

print "Importing module a"
var = ""

testb.py:

import testa
testa.var = "test"

testc.py:

import testa
print testa.var

Now in the python interpreter (or the main script, if you prefer):

>>> import testb
Importing module a
>>> import testc
test
>>>

So you see that the change in var made when importing b is actually seen in c.

I would suspect that your problem lies in whether and in what order your code is actually executed.

Upvotes: 2

Schuh
Schuh

Reputation: 1095

In file a.py define a class:

class A:
    class_var = False
    def __init__(self):
        self.object_var = False

Then in b.py import this and instantiate an object of class A:

from a import A
a = A()

Now you can access the attributes of the instance of a.

a.object_var = True

And you can access variables for the class A:

A.class_var = True

If you now check for:

a.class_var
-> True
a.object_var
-> True
another_instance = A()
another_instance.object_var
->False
another_instance.class_var
->True

Upvotes: 1

Related Questions