summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul McGuire <ptmcg@austin.rr.com>2019-07-07 01:37:21 -0500
committerPaul McGuire <ptmcg@austin.rr.com>2019-07-07 01:37:21 -0500
commit3f94c1245d318e0b18b991d72ab52d14f27cd4cf (patch)
tree47f1414c2714c74a0326b79b1fdcc63e3f4de55f
parentccfc76ac49189de3fe7de5062008fe12d981e5da (diff)
downloadpyparsing-git-3f94c1245d318e0b18b991d72ab52d14f27cd4cf.tar.gz
Add ParseResults.from_dict classmethod, for easy construction outside of parseString
-rw-r--r--CHANGES10
-rw-r--r--pyparsing.py25
2 files changed, 32 insertions, 3 deletions
diff --git a/CHANGES b/CHANGES
index cee1b99..f02d2e7 100644
--- a/CHANGES
+++ b/CHANGES
@@ -2,8 +2,8 @@
Change Log
==========
-Version 2.4.1 -
-----------------------
+Version 2.4.1 - July, 2019
+--------------------------
- A new shorthand notation has been added for repetition
expressions: expr[min, max], with '...' valid as a min
or max value:
@@ -58,6 +58,12 @@ Version 2.4.1 -
This form is only valid when used with the '|' operator.
+- Added ParseResults.from_dict classmethod, to simplify creation
+ of a ParseResults with results names. May be called with a dict
+ argument, or with a series of named arguments (or both). This
+ makes it easy to add a sub-level of named items to the parsed
+ tokens in a parse action.
+
- While investigating issue #93, I found that Or and
addCondition could interact to select an alternative that
is not the longest match. This is because Or first checks
diff --git a/pyparsing.py b/pyparsing.py
index 3d42289..27df353 100644
--- a/pyparsing.py
+++ b/pyparsing.py
@@ -96,7 +96,7 @@ classes inherit from. Use the docstrings for examples of how to:
"""
__version__ = "2.4.1"
-__versionTime__ = "05 Jul 2019 23:23 UTC"
+__versionTime__ = "07 Jul 2019 06:35 UTC"
__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
import string
@@ -112,6 +112,7 @@ import traceback
import types
from datetime import datetime
from operator import itemgetter
+import itertools
try:
# Python 3
@@ -1110,6 +1111,28 @@ class ParseResults(object):
def __dir__(self):
return (dir(type(self)) + list(self.keys()))
+ @classmethod
+ def from_dict(cls, other=None, **kwargs):
+ """
+ Helper classmethod to construct a ParseResults from either a dict or a sequence of named arguments,
+ preserving the name-value relations as results names.
+ """
+ if other is not None:
+ items = itertools.chain(other.items(), kwargs.items())
+ else:
+ items = kwargs.items()
+
+ def is_iterable(obj):
+ try: iter(obj)
+ except Exception: return False
+ else:
+ if PY_3:
+ return not isinstance(obj, (str, bytes))
+ else:
+ return not isinstance(obj, basestring)
+
+ return sum(cls([v], name=k, asList=is_iterable(v)) for k, v in items)
+
MutableMapping.register(ParseResults)
def col (loc,strg):