Parser or regex ?
Michael Spencer
mahs at telcopartners.com
Fri Dec 16 12:11:21 EST 2005
Fuzzyman wrote:
> Hello all,
>
> I'm writing a module that takes user input as strings and (effectively)
> translates them to function calls with arguments and keyword
> arguments.to pass a list I use a sort of 'list constructor' - so the
> syntax looks a bit like :
>
> checkname(arg1, "arg 2", 'arg 3', keywarg="value",
> keywarg2='value2', default=list("val1", 'val2'))
>
> Worst case anyway :-)
> ...
Perhaps you could simply use Python's parser - the syntax appears to be Python's.
e.g., a very quick hack using eval, which is easier without the list call, so
I'm cheating and replacing it with a list literal for now:
>>>
>>> source = """checkname(arg1, "arg 2", 'arg 3', keywarg="value",
... keywarg2='value2', default=["val1", 'val2'])"""
>>>
We need some way to ensure bare names don't cause NameErrors:
>>> class lazynames(dict):
... def __getitem__(self, key):
... if key in self:
... return dict.__getitem__(self, key)
... return "%s" % key # if name not found, return it as a str constant
...
>>> def checkname(*args, **kw):
... return args, kw
...
>>> d = lazynames(__builtins__ = None, checkname = checkname)
>>>
With this set up, you can parse in one line!
>>> eval(source, globals(), d)
(('arg1', 'arg 2', 'arg 3'), {'default': ['val1', 'val2'], 'keywarg': 'value',
'keywarg2': 'value2'})
>>>
If you don't like the risks of eval, then compiler.parse gives a form of the
parse output that is fairly easy to deal with
Cheers
Michael
More information about the Python-list
mailing list