Search code examples
pythonoopeval

Better way to return classes from corresponding strings


I'm writing a fantasy programming language for a game. Part of what the interpreter does is converts the code (a string) into command objects. For example, the following code:

set var 1

creates a variable called var with the value of 1. In the interpreter, this creates a new instance of the Set command class. Currently, I have a list of if statements to create commands:

    if packet == "set":
        return commands.Set
    elif packet == "get":
        return commands.Get
    elif packet == "print":
        return commands.Print
    elif packet == "goto":
        return commands.Goto
    elif packet == "add":
        return commands.Add

But this is a real pain when adding new commands. I have to add the command class, add it to a list of syntax, and add it to a table here.

I realized that eval could help me here, but I know that is looked down upon.

return eval("commands." + packet.capitalize())

Is there a better way to do this, or is eval okay in this usage?


Solution

  • Try this:

    return getattr(commands, packet.capitalize())