getting global variables from dictionary

George Sakkis george.sakkis at gmail.com
Sat Sep 27 04:29:43 CEST 2008


On Sep 26, 10:01 pm, icarus <rsa... at gmail.com> wrote:
> global_vars.py has the global variables
> set_var.py changes one of the values on the global variables (don't
> close it or terminate)
> get_var.py retrieves the recently value changed (triggered right after
> set_var.py above)
>
> Problem: get_var.py retrieves the old value, the built-in one but not
> the recently changed value in set_var.py.
>
> What am I doing wrong?
>
> ----global_vars.py---
> #!/usr/bin/python
>
> class Variables :
>         def __init__(self) :
>                 self.var_dict = {"username": "original username"}
>
> ---set_var.py ---
> #!/usr/bin/python
>
> import time
> import global_vars
>
> global_vars.Variables().var_dict["username"] = "new username"
> time.sleep(10)   #give enough time to trigger get_var.py
>
> ---get_var.py ---
> #!/usr/bin/python
> import global_vars
> print global_vars.Variables().var_dict.get("username")

First off, you don't import the set_var module anywhere; how do you
expect the value to change? Second, every time you do
"global_vars.Variables()" you create a brand new Variables() instance,
initialized with the original var_dict. The Variables() instance you
create at set_var.py is discarded in the very next line. Third, I have
no idea why you put the "time.sleep(10)" there.

By the way, Python is not Java; you don't have to make classes for
everything. A working version of your example would be:

----global_vars.py---

var_dict = {"username": "original username"}

---set_var.py ---
import global_vars
global_vars.var_dict["username"] = "new username"

---get_var.py ---
import global_vars
import set_var
print global_vars.var_dict.get("username")

$ python get_var.py
new username


HTH,
George



More information about the Python-list mailing list