Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Functions

Tags:

python

parsing

I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....

EDIT

This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?

like image 312
The.Anti.9 Avatar asked Sep 02 '25 05:09

The.Anti.9


1 Answers

Once you get the name of the function, use a dispatch dict to run the function:

def mysum(...): ...
def myotherstuff(...): ...

# create dispatch dict:
myfunctions = {'sum': mysum, 'stuff': myotherstuff}

# run your parser:
function_name, parameters = parse_result(line)

# run the function:
myfunctions[function_name](parameters)

Alternatively create a class with the commands:

class Commands(object):
    def do_sum(self, ...): ...
    def do_stuff(self, ...): ...
    def run(self, funcname, params):
        getattr(self, 'do_' + funcname)(params)

cmd = Commands()
function_name, parameters = parse_result(line)
cmd.run(function_name, parameters)

You could also look at the cmd module in the stdlib to do your class. It can provide you with a command-line interface for your language, with tab command completion, automatically.

like image 200
nosklo Avatar answered Sep 04 '25 17:09

nosklo