4

If you had two strings, like so ->

string1 = "get"  
string2 = "Feed"

So how would you use these 2 strings to call a function named -> getFeed() ?

3 Answers 3

7

Depending on where the function is, you can use one of these:

globals()[string1 + string2]()
locals()[string1 + string2]()
Sign up to request clarification or add additional context in comments.

2 Comments

Or, only as a last resort, eval(string1 + string2)() if it can be in arbitrary scope.
Oh no it's eval! Yes, that would also work. I imagine a responsible answerer would've said something about the importance of sanitizing input if these variables come from some other system, but it's 2am and I'm hungry.
3

If ImportedLib had your function getFeed(), you'd call it as such:

import ImportedLib
getattr(ImportedLib, string1+string2)()

Comments

2

Assume the function is located inside foo. Then call

getattr(foo, string1 + string2) ()

Comments

Your Answer

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.