1

For some reason, I have a list of strings that happen to be python built-in functions/methods. Example, somelist = ['list', 'insert', 'append']

I have some data, like data = 'I am a cat' Now, I want to do an operation from somelist on data. Example, list(data)

If I try to index from somelist[0], I am getting the str object 'list'. But I want the keyword list instead.

Is there any way to convert str object to keyword datatype? (Is there even a datatype for keywords?)

Jenkins
  • 71
  • 4

1 Answers1

2

One way you can achieve what you're looking for is with eval()

somelist = ['list', 'insert', 'append', 'pop']
data = 'I am a cat'

lst = eval(somelist[0] + '(data)')
print(lst)

ind = 2
eval('lst.' + somelist[1] + '(ind, data)')
print(lst)

eval('lst.' + somelist[2] + '(data)')
print(lst)

As you can see, eval() literally executes the command - in the form of string - that it got as an argument. This is very dangerous, and depending on your application, should be avoided (unless you check what you're executing very rigorously, or there are some other ways to maintain safety). Read this for a complete list of issues with eval(). You still need to, as far as I know, provide the framework for each command as above.

Another, safer way is the use if statements that recognize (or not) the element in somelist and turn them into a proper call,

somelist = ['list', 'insert', 'append', 'pop']
data = 'I am a cat'

lst2 = []
for op in somelist:
    if op == 'list':
        lst2 = list(data)
        print(lst2)
    elif op == 'insert':
        lst2.insert(3, data)
    elif op == 'append':
        lst2.append(data)
    else:
        print(op + ' is not defined')

This is safe since you have control over what can be called. You can turn it into a function, with optional or keyword arguments, and improve it's robustness. This is just an example to show you the concept.

atru
  • 4,699
  • 2
  • 18
  • 19