From dictionary keys to variables

Michael Foord fuzzyman at gmail.com
Tue Oct 12 03:20:35 EDT 2004


Jeff Shannon <jeff at ccvcorp.com> wrote in message news:<10mme8ars7bdaeb at corp.supernews.com>...
> Michael Foord wrote:
> 
> >I use a module called COnfigObj to read my config files into python.
> >It exposes them as a dictionary.
> >
> >I often find myself writing code like :
> >
> >valuelist = ['name1', 'name2', 'name3'....]
> >config = ConfigObj(filename, configspec=valuelist)
> >name1 = config['name1']
> >name2 = config['name2']
> >name3 = config['name3']
> >  
> >
> 
> Any reason why it's necessary to define variables instead of just using 
> the dict?  You're probably not really saving anything by doing this...  
> there *might* be a slight savings in typing if you use the names 
> numerous times, but directly accessing the dictionary makes it clearer 
> where your values are coming from.  And dict lookups are fast, so unless 
> you're using these valuables repeatedly inside a tight loop, you won't 
> get significant speed savings.  (If you *are* using some inside a tight 
> loop, then it's sensible to hoist the lookup out of the loop, but don't 
> do this until you know that that loop is a significant source of 
> slowdown -- as they say, premature optimization is the root of all evil.)
> 

It's not really optimisation. There are two factors, I write lot's of
little scripts that pull there paths/config options out of a config
file in this way. With something like the above or 'globals()[entry]'
I can just cut and paste a chunk of code. That means I can add/change
the variable names (which correspond to keywords in the config file)
by just changing the name once in the 'valuelist'. I can then access
the variable directly without having to keep *typing* the
config['..... bit.. The only optimisation is on my wrist !!

Anyway, thanks. You may still be right of course...

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantibots/pythonutils.html

> Jeff Shannon
> Technician/Programmer
> Credit International



More information about the Python-list mailing list