Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: change global variable from within another file

Tags:

python

In my main class I use a global variable ADDRESS that is defined in another file called config.py. I want to change the value of ADDRESS from within my main class, by calling a function in config.py.

In my main class I have:

from config import ADDRESS, change_address
change_address("192.168.10.100")
print("new address " + ADDRESS)

In my config file I have the following:

ADDRESS = "0.0.0.0"

def change_address(address):
    global ADDRESS
    ADDRESS = address
    print("changed address to: " + ADDRESS)

The print statement in my config file correctly prints the new address of 192.168.10.100. However, the print statement in my main class prints 0.0.0.0. What am I missing here?

like image 699
crusarovid Avatar asked Dec 05 '17 19:12

crusarovid


1 Answers

All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's name-space. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how name-spaces work. It is like doing the following:

>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}

The simplest solution? Don't clobber name-spaces:

import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)
like image 77
juanpa.arrivillaga Avatar answered Oct 07 '22 14:10

juanpa.arrivillaga