getting global variables from dictionary
Chris Rebert
clp at rebertia.com
Fri Sep 26 22:17:38 EDT 2008
When you do "Variables()" in your code, you're making a new instance
of that class that has no relation to any other instances. This is the
cause of your problem. To just reference a class, use just
"Variables". But that doesn't help in this case because var_dict is an
instance variable, not a class variable.
On Fri, Sep 26, 2008 at 7:01 PM, icarus <rsarpi at gmail.com> wrote:
> global_vars.py has the global variables
No it doesn't, it just defines a class. The class itself (but NOT its
instances) is a module-level global.
> set_var.py changes one of the values on the global variables (don't
> close it or terminate)
No, it just instanciates the Variables class and then manipulates the
instance, which is then GC-ed because it's no longer referenced
anywhere, even in set_var.
> get_var.py retrieves the recently value changed (triggered right after
> set_var.py above)
No, it creates an entirely new instance of Variables and then fetches
the value from that instance (which is still using the default value
because this new instance has never been modified).
>
> 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?
Try just making var_dict a module-level variable in global_vars.py and
then manipulating that rather than this unnecessary mucking about with
Variables(). Alternatively, make var_dict a *class* variable of
Variables by removing it from __init__ and just putting 'var_dict =
{"username": "original username"}' in the raw class body of Variables;
And then remove the parentheses after Variables as I mentioned in the
beginning.
Regards,
Chris
>
> ----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")
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Follow the path of the Iguana...
http://rebertia.com
More information about the Python-list
mailing list