473,507 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

From dictionary keys to variables

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']
..
..

Now is there any reason not to 'cheat' and use __main__.__dict__ to
create the variables ?

valuelist = ['name1', 'name2', 'name3'....]
config = ConfigObj(filename, configspec=valuelist)
import __main__
for entry in valuelist:
__main__.__dict__[entry] = config[entry]

(The configspec is optional - but helps with ConfigObj).

Regards,
Fuzzy

http://www.voidspace.org.uk/at;antib...thonutils.html
Jul 18 '05 #1
5 1499
Michael Foord wrote:
Why cheat? There is legal way to do that:

for entry in valuelist:
globals()[entry] = config[entry]
Now is there any reason not to 'cheat' and use __main__.__dict__ to
create the variables ?

valuelist = ['name1', 'name2', 'name3'....]
config = ConfigObj(filename, configspec=valuelist)
import __main__
for entry in valuelist:
__main__.__dict__[entry] = config[entry]



--
Timothy Babytch
--
You know you've achieved perfection in design,
not when you have nothing more to add,
but when you have nothing more to take away.
Jul 18 '05 #2
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.)

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #3
Timothy Babytch <ti*@zeos.net> wrote in message news:<ck***********@news.dg.net.ua>...
Michael Foord wrote:
Why cheat? There is legal way to do that:

for entry in valuelist:
globals()[entry] = config[entry]
Now is there any reason not to 'cheat' and use __main__.__dict__ to
create the variables ?

valuelist = ['name1', 'name2', 'name3'....]
config = ConfigObj(filename, configspec=valuelist)
import __main__
for entry in valuelist:
__main__.__dict__[entry] = config[entry]


Ahh... I didn't realise you could do assignment into globals().........

Thanks

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html


--
Timothy Babytch

Jul 18 '05 #4
Jeff Shannon <je**@ccvcorp.com> wrote in message news:<10*************@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/atlantib...thonutils.html
Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #5
Michael Foord wrote:
Jeff Shannon <je**@ccvcorp.com> wrote in message news:<10*************@corp.supernews.com>...

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 !!


Oof. Don't cut and paste code if you can avoid it. Instead, make
utility modules and import them. Much *much* safer. Every time you cut
and paste, you run the risk of forgetting to rename something, or
copying a name that isn't defined in your new script, or any number of
other minor little glitches. (I do much of my workday programming in an
environment that doesn't support modularization well at all, and we have
no real options for code reuse other than to either cut and paste, or
retype from scratch. I know first-hand just how easy it is to make
mistakes when cutting and pasting, because I do it all the freakin'
time.... bleah! I *so* wish I could use Python for all of that...)

And really, if you're trading readability for typing ease, you're
getting a bad deal. You're very likely to read that code many more
times than you're going to type it, so a slight addition to the
difficulty of reading and understanding it will soon make up for a bit
of extra typing. More importantly, if there's any chance that anyone
*else* will ever look at your code, it's much nicer for *them* to not
have to figure out how the heck this variable got here... And even if
your code is something that you expect to be a solitary project that'll
never be distributed to anyone else, it's still a good idea to get in
the habit of writing readable code. If nothing else, you never know
when you might want to post segments of it to c.l.py for
assistance/advice. ;)

(All of this being strictly my personal opinion, of course, which is
probably worth about as much as you paid for it....)

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3575
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
7
1991
by: Thomas Philips | last post by:
I want to print "1 spam 4 you" using a formatted string that gets its inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, I write >>> x="%('n1')d %('s1')s %('n2')d you" >>> x...
20
3522
by: Brian Burgess | last post by:
Hi all, Anyone know if this is possible? If so, on which page would the cookie be? .. On the page calling a function defined in the include file? thanks in advance.. -BB
4
3344
by: Noah | last post by:
I have a dictionary that I would like to expand to satisfy a function's agument list. I can used the ** syntax to pass a dictionary, but this only works if each key in the dictionary matches an...
90
10699
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
1
4492
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type...
4
2309
by: Betina Andersen | last post by:
I have a dictionary object, then I create a new dictionary object and sets it equal to my original, then I pass the new dictionary object to a function that changes some of my values - but then my...
18
2947
by: Marko.Cain.23 | last post by:
Hi, I create a dictionary like this myDict = {} and I add entry like this: myDict = 1 but how can I empty the whole dictionary? Thank you.
15
6505
by: damiensawyer | last post by:
Hi, I am creating a class (from a base class) that needs to trigger events (code at bottom). I am instatiating the classes and wiring up the events as follows. clsDetermineConnection oDC =...
12
3493
by: Howard Swope | last post by:
This problem has been bugging me for a while. I have created a collection class and implemented it in a C# library. If I inherit from this class in another C# assembly and it works, but if I...
0
7221
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7109
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7029
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7481
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5039
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
411
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.