Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert two strings to give you a function name in Python

Tags:

python

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() ?

like image 201
Sai Krishna Avatar asked Dec 17 '22 11:12

Sai Krishna


2 Answers

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

globals()[string1 + string2]()
locals()[string1 + string2]()
like image 110
Jordan Avatar answered Feb 09 '23 01:02

Jordan


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

import ImportedLib
getattr(ImportedLib, string1+string2)()
like image 26
K Mehta Avatar answered Feb 09 '23 01:02

K Mehta