getting global variables from dictionary
Ben Finney
bignose+hates-spam at benfinney.id.au
Fri Sep 26 22:28:40 EDT 2008
icarus <rsarpi at gmail.com> writes:
> 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.
That's because you're making a new instance each time; each instance
carries its own state.
For a collection of attributes that should share state, probably the
simplest way is to use attributes of a module.
> ----global_vars.py---
> #!/usr/bin/python
>
> class Variables :
> def __init__(self) :
> self.var_dict = {"username": "original username"}
These aren't "global variables"; they still need to be imported, like
anything else from a module. Better to name the module by intent; e.g.
if these are configuration settings, a module name of 'config' might
be better.
Also, this module presumably isn't intended to be run as a program;
don't put a shebang line (the '#!' line) on files that aren't run as
programs.
===== config.py =====
# -*- coding: utf-8 -*-
# Name of the front-end user
username = "original username"
# Amount of wortzle to deliver
wortzle_amount = 170
=====
> ---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
===== set_config.py =====
# -*- coding: utf-8 -*-
import config
def set_user():
config.username = "new username"
=====
> ---get_var.py ---
> #!/usr/bin/python
> import global_vars
> print global_vars.Variables().var_dict.get("username")
===== get_config.py =====
# -*- coding: utf-8 -*-
import config
def get_user():
return config.username
=====
The 'config' module, imported by both of the other modules, maintains
state:
>>> import config
>>> print config.username
original username
>>> import set_config
>>> set_config.set_user()
>>> print config.username
new username
>>> import get_config
>>> print get_config.get_user()
new username
--
\ “You can't have everything; where would you put it?” —Steven |
`\ Wright |
_o__) |
Ben Finney
More information about the Python-list
mailing list