an apply question

Tim Hochberg tim.hochberg at ieee.org
Tue Dec 5 19:36:48 EST 2000


"Alan Marchand" <malan at club-internet.fr> wrote in message
news:90jsj0$24o$1 at front6.grolier.fr...
> In Python 2.0:
>
> What am I doing wrong?

Well a string is not a function, and you are trying to call a string as a
function. So the error you're getting makes sense.

It's not entirely clear what you want to do; I see two possibilities: the
first is that you are trying to look up the name given by a string and call
it. This could be accomplished by modifying the second part of your program
as follows:

for key, name in MyMap.items():
    if key == "Key3":
        func = getattr(globals(), name) # look up the function
        func() # or apply( func, ( ) )


The other possibility is that you want to actually store the functions in
your map. In this case, you could use.

def func1 ( ):
     print "Here's func1"
def func2 ( ):
     print "Here's func2"
def func3 ( ):
     print "Here's func3"
def func4 ( ):
     print "Here's func4"

 MyMap = {
 'Key1' : func1,
 'Key2' : func2,
 'Key3' : func3,
 'Key4' : func4
 }
#...

Note that there are no quotes around the functions in MyMap and that the
functions come before they are referred to.


-tim

> #!/bin/env python
> #############
> MyMap = {
> 'Key1' : 'func1',
> 'Key2' : 'func2',
> 'Key3' : 'func3',
> 'Key4' : 'func4'
> }
>
> def func1 ( ):
>     print "Here's func1"
>
> items = MyMap.items( )
> for x in range( len(items) ):
>     key, func = items[x]
>     if key == "Key3":
>         apply( func, ( ) )
> -------------------------
> c:\devpy\python test.py
>
> Traceback (most recent call last):
>   File "test.py", line 17, in ?
>     apply( func, ( ) )
> TypeError: Call of non-function (type string)
>
> Thanks.
> Alan.
>
>





More information about the Python-list mailing list