I want to use a string as an already exists list function. For example i got from a user as input: 'append'
How can i use this string as a function directly?
For example:
function_name = str(input(n)) # let say it is append
arr = []
arr.function_name(9) #Of course it is not working because it is string. Not a function.
CodePudding user response:
Use getattr
.
>>> a = []
>>> getattr(a, 'append')(1)
>>> a
[1]
That being said, it's not the best idea to execute arbitrary code based on user input. You should check the input against a collection of allowed methods first.
CodePudding user response:
All functions are attributes of the respective object. You can use the getattr
function to get the function callable and then call it.
For Eg. ,
function_name = str(input("")) # let say it is append
arr = []
#Get the attribute and call it
# You can check if callable(function_to_call) to make sure its a function as well.
function_to_call = getattr(arr, function_name)
function_to_call(10)
print(arr)
CodePudding user response:
The method you are using is not possible.
But you can use this method instead...
function_name = str(input(n))
arr = []
if function_name == "append":
arr.append(9)
or you can use getattr
:
function_name = str(input(n))
arr = []
getattr(arr, fucntion_name)(9)