Is there a way to pass function name as a variable and call it as a fucntion. For example, converting a tuple to a list by passing list as a variable:
l=(1,2)
x=list
b=%s(l)%(x) #list(l)
edited
Sorry for giving you only half of the problem. A user inputs the function name like this
l=(1,2)
f=raw_input("Enter the name:")
len(f(l))
TypeError: 'str' object is not callable
2 Answers 2
Yes, you can assign a function name to a variable and then call it as a function:
l = (1,2)
x = list
answer = x(l)
print(answer)
Output
[1, 2]
Comments
If your variable is a string representing a name, you can look it up using globals:
x_name = 'list'
x = globals()[x_name]
y = x((1,2))
In the latter case, you can also use eval, but it isn't recommended, because eval is evil.
(Note that list is a type, not a function, but is callable nevertheless, so it works.)
b=%s(l)%(x). But you could dox(l).b = x(l)is the easy way. You don't need the name of the function to call it; you just need the function itself. Since you sayx=list,xnow refers to that function, so you can usex(l)just like that.