Re: [Pyparsing] Forward() causing odd behaviour
Brought to you by:
ptmcg
From: Ralph C. <ra...@in...> - 2011-06-22 22:36:05
|
Hi Cathal, > I have found something very weird. When I type the below into my > python console I get the following error: ParseException: Expected ")" > (at char 3), (line:1, col:4) > > from pyparsing import * > function = Forward() > function = '#' + Word(nums) + Group(Literal('(') + Optional(function)) + Literal(')') > function.parseString('#0(#1())', True) I get that too, and it seems correct. > However, if I then re-enter everything accept the line: function = > Forward() it works as I initially expected it to. > > from pyparsing import * > function = '#' + Word(nums) + Group(Literal('(') + Optional(function)) + Literal(')') > function.parseString('#0(#1())', True) > Out[6]: (['#', '0', (['(', '#', '1', (['('], {}), ')'], {}), ')'], {}) I get >>> from pyparsing import * >>> function = '#' + Word(nums) + Group(Literal('(') + Optional(function)) + Literal(')') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'function' is not defined >>> which again seems correct. It seems you're entering these lines into the same Python interpreter in which you've already defined function. IOW, your two tests are not isolated; the second is altered by the leftovers of the first. Again, printing function in both cases may have given a clue. First time, >>> print function {"#" W:(0123...) Group:({"(" [Forward: None]}) ")"} second time, >>> print function {"#" W:(0123...) Group:({"(" [{"#" W:(0123...) Group:({"(" [Forward: None]}) ")"}]}) ")"} So the second one still isn't right: >>> function.parseString('#0(#1(#2()))', True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.6/pyparsing.py", line 1076, in parseString raise exc pyparsing.ParseException: Expected ")" (at char 3), (line:1, col:4) >>> You haven't got a recursive grammar, just one two levels deep. > How do I make this work without having to enter the first sequence and > then the second sequence of modified statements? from pyparsing import * f = Forward() function = '#' + Word(nums) + Group(Literal('(') + Optional(f)) + Literal(')') f << function function.parseString('#0(#1())', True) You must keep a reference to the Forward() so that you can "fill it in" later. You can't do this is you through it away by immediately re-assigning to function, hence my use of f. Note, the Forward is no longer None. >>> print function {"#" W:(0123...) Group:({"(" [Forward: {"#" W:(0123...) Group:({"(" [...]}) ")"}]}) ")"} Cheers, Ralph. |