Search code examples
pythonpython-3.xeval

Calling a string as a function using eval()


I wish to call append function for a list with append passed in as a string. For instance:

List = [1,2]
func = 'append'
value = 3
# I wish to call List.append(value) 

I know there is a way using eval but, I am unable to figure it out.


Solution

  • Use getattr.

    List = [1,2]
    func = 'append'
    value = 3
    
    f = getattr(List, func)
    f(value)
    print(List)