Rocco J Pietrofesa
Rocco J Pietrofesa

Reputation: 3

How to take a string and use it as an identifier to call a function?

I have created an autograder for my classes that uses a command line argument to call the associated function for that problem set. I need to extract the command line argument as a string, and then use it as a function call. In the example I'm assigning the string to pset and then calling pset and passing studentFile as the argument. The problem is that the interpreter sees it as a string and not an identifier.

this is a picture of my code

if len(sys.argv) == 2:
    try:
        # find and store the file
        studentFile = helpers.findInSubdirectory(sys.argv[1])
        for i in studentFile.split('/'):
            if i.endswith('.py'):
                pset = i[:-3]
        pset(studentFile)

Upvotes: 0

Views: 205

Answers (1)

kojiro
kojiro

Reputation: 77197

An unsafe way to do this would be to use eval or look at the globals() dictionary. A slightly safer way would be to create a string-to-function mapping in a dictionary, and look up the function from the mapping.

def foo():
    print('hi')

def bar():
    print('see you')

funs = { 'foo': foo, 'bar': bar }
funs['foo']()

Upvotes: 2

Related Questions