I would like to execute a named function on a python object by variable name. For example, let’s say I’m reading in input that looks something like this:
enqueue 1 enqueue 12 enqueue 5 enqueue 9 sort reverse dequeue print
Afterwards, we should see:
[9,5,1]
Let’s say we need to implement a data structure that consumes this input. Fortunately, all of this behavior already exists within the built-in list datatype. What we can do is extend the built-in list to map the appropriate methods, like so:
class qlist(list): def enqueue(self, v): self.insert(0,v) def dequeue(self): return self.pop() def print(self): print(self)
The sort and reverse methods are already built-in to list, so we don’t need to map them. Now, we simply need a driver program that reads and processes commands to our new qlist class. Rather than map out the different commands in if/else blocks, or use eval(), we can simply use getattr, for example:
if __name__ == '__main__': thelist = qlist() while line in sys.stdin: cmd = line.split() params = (int(x) for x in cmd[1:]) getattr(thelist, cmd[0])(*params)