Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for defining PyParsing field names

I have a few pyparsing tokens defined as follows:

field = Word(alphas + "_").setName("field")

Is there really no shorthand for this?

Furthermore, this does not seem to work, the dictionary returned by expression.parseString() is always an empty one.

like image 392
Kimvais Avatar asked Feb 03 '26 13:02

Kimvais


2 Answers

You are confusing setName and setResultsName. setName assigns a name to the expression so that exception messages are more meaningful. Compare:

>>> integer1 = Word(nums)
>>> integer1.parseString('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python26\lib\site-packages\pyparsing-1.5.6-py2.6.egg\pyparsing.py", line 1032, in parseString
    raise exc
pyparsing.ParseException: Expected W:(0123...) (at char 0), (line:1, col:1)

and:

>>> integer2 = Word(nums).setName("integer")
>>> integer2.parseString('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python26\lib\site-packages\pyparsing-1.5.6-py2.6.egg\pyparsing.py", line 1032, in parseString
    raise exc
pyparsing.ParseException: Expected integer (at char 0), (line:1, col:1)

setName gives a name to the expression itself.

setResultsName on the other hand gives a name to the parsed data that is returned, like named fields in a regex.

>>> expr = integer.setResultsName('age') + integer.setResultsName('credits')
>>> data = expr.parseString('20 110')
>>> print data.dump()
['20', '110']
- age: 20
- credits: 110

And as @Kimvais has mentioned, there is a shortcut for setResultsName:

>>> expr = integer('age') + integer('credits')

Note also that setResultsName returns a copy of the expression - that is the only way that using the same expression multiple times with different names works.

like image 150
PaulMcG Avatar answered Feb 06 '26 01:02

PaulMcG


field = Word(alphas + "_")("field")

seems to work.

like image 34
Kimvais Avatar answered Feb 06 '26 02:02

Kimvais