2

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
asked Mar 18, 2016 at 12:54
2
  • 2
    I don't understand what you mean with b=%s(l)%(x). But you could do x(l). Commented Mar 18, 2016 at 12:55
  • 1
    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 say x=list, x now refers to that function, so you can use x(l) just like that. Commented Mar 18, 2016 at 12:56

2 Answers 2

3

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]
answered Mar 18, 2016 at 12:56
Sign up to request clarification or add additional context in comments.

Comments

3

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.)

answered Mar 18, 2016 at 12:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.