stackoverflow about python dynameic inovke function with it's name
时间:2010-10-05 来源:lexus
Stack Overflow
Python: Passing a function name as an argument in a function
up vote 3 down vote favorite |
I am trying to pass the name of a function into another function as an argument but I get an error: "TypeError: 'str' object is not callable". Here is a simplified example of the problem: def doIt(a, func, y, z): When I call doIt like so: var = 'dork1' I get: Traceback (most recent call last):python
|
||||||||||||||
|
6 Answers
oldest newest votesup vote 5 down vote |
If you want to pass the function's name, as you said and you're doing, of course you can't call it -- why would one "call a name"? It's meaningless. If you want to call it, pass the function itself, that is, most emphatically not var = 'dork1' but rather var = dork1 without quotes! Edit: the OP wonders in a comment (!) how to get a function object given the function name (as a string). As it happens I just showed how to do that in a tutorial I taught at OSCON (from which I'm just back) -- get the slides from here and see page 47, "Lazy-loading callbacks": class LazyCallable(object): So you could pass LazyCallable('somemodule.dork1') and live happily ever after. If you don't need to deal with the module of course (what a weird architecture that must imply!-) it's easy to adjust this code.
|
||||||||
|
up vote 2 down vote |
Don't pass the name of a function. Pass the function. fun = dork1
|
||||
|
up vote 1 down vote |
var = 'dork1' In this example, var is a string. The doIt function "calls" its second argument (for which you pass var). Pass a function instead.
|
||||||||||||||||||||||||||
|
up vote 0 down vote |
If you have to pass it as a string you can call it with: globals()['dork1'](arg1,arg2,arg3)
|
||||
|
up vote -1 down vote |
Functions are first-class objects in python. Do this: var = dork1 If you must pass a string, such as user input, then: globals()[var] will look up the function object.
|
||||
|
up vote 0 down vote |
You probably shouldn't do this, but you can get the function using eval() for example, to use len, eval("len")(["list that len is called on"])
|
||||
|