[Tutor] creating variables from the 'key' of a dictionary. Further
explainations
Jeff Shannon
jeff at ccvcorp.com
Fri Jul 2 21:43:11 EDT 2004
Larry Blair wrote:
> This way if we added a parameter I could add the code only to the function
> to add the key and value to the dictionary. Then part 2 would automatically
> create the new variable and I would not have to change code but in one
> place.
>
> the code would look like
>
> for pr, item in para.item():
> some-magic-function where a variable would appear with a value. i.e.
> source_server = 'cm05' etc until the end of the dictionary.
Why would you want to create local/global variables? Why not just use
the value straight out of the dictionary? In other words, everywhere
where you're thinking of using "source_server", why not just use
"param['source_server']" instead? This will save you a step, spare
you headaches fiddling with locals()/globals(), and will be much less
likely to result in surprising side-effects.
For that matter, if you really don't care for dictionary syntax, you
can set up your parameters as global to a separate module, like so:
-------- param.py --------
source_server = 'cm05'
dest_server = 'tm02'
--------------------------
-------- main.py ---------
import param
print param.source_server
--------------------------
Either way, whether you do this or use a dictionary, you're
conveniently isolating all of your parameters. If you need to change
anything, you can edit param.py and reload() it.
To quote the Zen of Python, "Namespaces are one honking great idea --
let's do more of those!" By keeping those parameters in a separate
file, and deliberately accessing them as a separate thing, you're
introducing a separate namespace and thereby helping to keep things
nice and organized. And organization is easier to maintain. :)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list