Trying to set up dictionary to map to functions

Peter Otten __peter__ at web.de
Tue Dec 8 16:54:24 EST 2009


Randy Belt wrote:

> I have a small test program written trying to set up a dictionary that
> points keys to functions.  It is working.  However, in the process of
> creating it I noticed a weird problem.  The problem is that this IS
> WORKING and I think it shouldn't be.
> 
> ~ Here is the input config file code ~  its called config.file and is
> referenced from the script.
> 
> [MAPS]
> relmap = 1
> posmap = 1
> asnmap = 1
> 
> ~ Here is the code that is working but I feel that it shouldn't be ~
> 
> import ConfigParser
> config = ConfigParser.ConfigParser()
> config.read("config.file")
> sections = config.sections()
> print config.options('MAPS')
> def posmap():
>     print "posmap function"
> def relmap():
>     print "relmap function"
> def asnmap():
>     print "asnmap function"
> for value in config.options('MAPS'):
>     value
> map_library = {
>                'posmap': posmap()
>               ,'relmap': relmap()
>               ,'asnmap': asnmap()
>               }

I can only guess what you are trying to do here. A dictionary like

d = {"key": func()}

is equivaluent to

value = func()
d = {"key": value}

i. e. you put the function's result into the dict, not the function itself. 
You can verify that for your program -- if you remove one of the three 
entries from the config file it will still invoke all three functions.

If you want the config file to control which functions should be invoke 
change your code as follows:

map_library = {"posmap": posmap, "relmap": relmap, "asnmap": asnmap}
for value in config.options("MAPS"):
    map_library[value]()

Peter




More information about the Python-list mailing list