| # Gaudi Framework, version v25r0 |

Home |  | Generated: Mon Feb 17 2014

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- Class List
- Class Index
- Class Hierarchy
- Class Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes | List of all members
pyparsing.ParserElement Class Reference
Inheritance diagram for pyparsing.ParserElement:
[legend]
Collaboration diagram for pyparsing.ParserElement:
[legend]

## Public Member Functions
def | setDefaultWhitespaceChars
def | __init__
def | copy
def | setName
def | setResultsName
def | setBreak
def | setParseAction
def | addParseAction
def | setFailAction
def | preParse
def | parseImpl
def | postParse
def | tryParse
def | resetCache
def | enablePackrat
def | parseString
def | scanString
def | transformString
def | searchString
def | __add__
def | __radd__
def | __sub__
def | __rsub__
def | __mul__
def | __rmul__
def | __or__
def | __ror__
def | __xor__
def | __rxor__
def | __and__
def | __rand__
def | __invert__
def | __call__
def | suppress
def | leaveWhitespace
def | setWhitespaceChars
def | parseWithTabs
def | ignore
def | setDebugActions
def | setDebug
def | __str__
def | __repr__
def | streamline
def | checkRecursion
def | validate
def | parseFile
def | getException
def | __getattr__
def | __eq__
def | __ne__
def | __hash__
def | __req__
def | __rne__

## Public Attributes
| parseAction
| failAction
| strRepr
| resultsName
| saveAsList
| skipWhitespace
| whiteChars
| copyDefaultWhiteChars
| mayReturnEmpty
| keepTabs
| ignoreExprs
| debug
| streamlined
| mayIndexError
| errmsg
| modalResults
| debugActions
| re
| callPreparse
| callDuringTry
| name
| myException

## Static Public Attributes
string | DEFAULT_WHITE_CHARS " \n\t\r"
tuple | setDefaultWhitespaceChars staticmethod(setDefaultWhitespaceChars)
tuple | resetCache staticmethod(resetCache)
tuple | enablePackrat staticmethod(enablePackrat)

## Private Member Functions
def | _normalizeParseActionArgs
def | _skipIgnorables
def | _parseNoCache
def | _parseCache

## Private Attributes
| __dict__

## Static Private Attributes
tuple | _normalizeParseActionArgs staticmethod(_normalizeParseActionArgs)
| _parse _parseNoCache
dictionary | _exprArgCache {}
| _packratEnabled False

## Detailed Description

    Abstract base level parser element class.

Definition at line 666 of file pyparsing.py.

## Constructor & Destructor Documentation

def pyparsing.ParserElement.__init__ | ( |  | self,
|  |  | savelist = `False`
| ) |  |

Definition at line 676 of file pyparsing.py.

676
677 def __init__( self, savelist=False ):
678 self.parseAction = list()
679 self.failAction = None
680 #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
681 self.strRepr = None
682 self.resultsName = None
683 self.saveAsList = savelist
684 self.skipWhitespace = True
685 self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
686 self.copyDefaultWhiteChars = True
687 self.mayReturnEmpty = False # used when checking for left-recursion
688 self.keepTabs = False
689 self.ignoreExprs = list()
690 self.debug = False
691 self.streamlined = False
692 self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
693 self.errmsg = ""
694 self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
695 self.debugActions = ( None, None, None ) #custom debug actions
696 self.re = None
697 self.callPreparse = True # used to avoid redundant calls to preParse
698 self.callDuringTry = False

## Member Function Documentation

def pyparsing.ParserElement.__add__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of + operator - returns And

Definition at line 1153 of file pyparsing.py.

1153
1154 def __add__(self, other ):
1155 """Implementation of + operator - returns And"""
1156 if isinstance( other, basestring ):
1157 other = Literal( other )
1158 if not isinstance( other, ParserElement ):
1159 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1160 SyntaxWarning, stacklevel=2)
1161 return None
1162 return And( [ self, other ] )

def pyparsing.ParserElement.__and__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of & operator - returns Each

Definition at line 1285 of file pyparsing.py.

1285
1286 def __and__(self, other ):
1287 """Implementation of & operator - returns Each"""
1288 if isinstance( other, basestring ):
1289 other = Literal( other )
1290 if not isinstance( other, ParserElement ):
1291 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1292 SyntaxWarning, stacklevel=2)
1293 return None
1294 return Each( [ self, other ] )

def pyparsing.ParserElement.__call__ | ( |  | self,
|  |  | name
| ) |  |

    Shortcut for setResultsName, with listAllMatches=default::
         userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
       could be written as::
         userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")

Definition at line 1309 of file pyparsing.py.

1309
1310 def __call__(self, name):
1311 """Shortcut for setResultsName, with listAllMatches=default::
1312 userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
1313 could be written as::
1314 userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
1315 """
1316 return self.setResultsName(name)

def pyparsing.ParserElement.__eq__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1420 of file pyparsing.py.

1420
1421 def __eq__(self,other):
1422 if isinstance(other, ParserElement):
1423 return self is other or self.__dict__ == other.__dict__
1424 elif isinstance(other, basestring):
1425 try:
1426 self.parseString(_ustr(other), parseAll=True)
1427 return True
1428 except ParseBaseException:
1429 return False
1430 else:
1431 return super(ParserElement,self)==other

def pyparsing.ParserElement.__getattr__ | ( |  | self,
|  |  | aname
| ) |  |

Definition at line 1413 of file pyparsing.py.

1413
1414 def __getattr__(self,aname):
1415 if aname == "myException":
1416 self.myException = ret = self.getException();
1417 return ret;
1418 else:
1419 raise AttributeError("no such attribute " + aname)

def pyparsing.ParserElement.__hash__ | ( |  | self | ) |

Definition at line 1435 of file pyparsing.py.

1435
1436 def __hash__(self):
1437 return hash(id(self))

def pyparsing.ParserElement.__invert__ | ( |  | self | ) |

    Implementation of ~ operator - returns NotAny

Definition at line 1305 of file pyparsing.py.

1305
1306 def __invert__( self ):
1307 """Implementation of ~ operator - returns NotAny"""
1308 return NotAny( self )

def pyparsing.ParserElement.__mul__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1193 of file pyparsing.py.

1193
1194 def __mul__(self,other):
1195 if isinstance(other,int):
1196 minElements, optElements = other,0
1197 elif isinstance(other,tuple):
1198 other = (other + (None, None))[:2]
1199 if other[0] is None:
1200 other = (0, other[1])
1201 if isinstance(other[0],int) and other[1] is None:
1202 if other[0] == 0:
1203 return ZeroOrMore(self)
1204 if other[0] == 1:
1205 return OneOrMore(self)
1206 else:
1207 return self*other[0] + ZeroOrMore(self)
1208 elif isinstance(other[0],int) and isinstance(other[1],int):
1209 minElements, optElements = other
1210 optElements -= minElements
1211 else:
1212 raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
1213 else:
1214 raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
1215
1216 if minElements < 0:
1217 raise ValueError("cannot multiply ParserElement by negative value")
1218 if optElements < 0:
1219 raise ValueError("second tuple value must be greater or equal to first tuple value")
1220 if minElements == optElements == 0:
1221 raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
1222
1223 if (optElements):
1224 def makeOptionalList(n):
1225 if n>1:
1226 return Optional(self + makeOptionalList(n-1))
1227 else:
1228 return Optional(self)
1229 if minElements:
1230 if minElements == 1:
1231 ret = self + makeOptionalList(optElements)
1232 else:
1233 ret = And([self]*minElements) + makeOptionalList(optElements)
1234 else:
1235 ret = makeOptionalList(optElements)
1236 else:
1237 if minElements == 1:
1238 ret = self
1239 else:
1240 ret = And([self]*minElements)
1241 return ret

def pyparsing.ParserElement.__ne__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1432 of file pyparsing.py.

1432
1433 def __ne__(self,other):
1434 return not (self == other)

def pyparsing.ParserElement.__or__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of | operator - returns MatchFirst

Definition at line 1245 of file pyparsing.py.

1245
1246 def __or__(self, other ):
1247 """Implementation of | operator - returns MatchFirst"""
1248 if isinstance( other, basestring ):
1249 other = Literal( other )
1250 if not isinstance( other, ParserElement ):
1251 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1252 SyntaxWarning, stacklevel=2)
1253 return None
1254 return MatchFirst( [ self, other ] )

def pyparsing.ParserElement.__radd__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of + operator when left operand is not a ParserElement

Definition at line 1163 of file pyparsing.py.

1163
1164 def __radd__(self, other ):
1165 """Implementation of + operator when left operand is not a ParserElement"""
1166 if isinstance( other, basestring ):
1167 other = Literal( other )
1168 if not isinstance( other, ParserElement ):
1169 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1170 SyntaxWarning, stacklevel=2)
1171 return None
1172 return other + self

def pyparsing.ParserElement.__rand__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of & operator when left operand is not a ParserElement

Definition at line 1295 of file pyparsing.py.

1295
1296 def __rand__(self, other ):
1297 """Implementation of & operator when left operand is not a ParserElement"""
1298 if isinstance( other, basestring ):
1299 other = Literal( other )
1300 if not isinstance( other, ParserElement ):
1301 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1302 SyntaxWarning, stacklevel=2)
1303 return None
1304 return other & self

def pyparsing.ParserElement.__repr__ | ( |  | self | ) |

Definition at line 1378 of file pyparsing.py.

1378
1379 def __repr__( self ):
1380 return _ustr(self)

def pyparsing.ParserElement.__req__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1438 of file pyparsing.py.

1438
1439 def __req__(self,other):
1440 return self == other

def pyparsing.ParserElement.__rmul__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1242 of file pyparsing.py.

1242
1243 def __rmul__(self, other):
1244 return self.__mul__(other)

def pyparsing.ParserElement.__rne__ | ( |  | self,
|  |  | other
| ) |  |

Definition at line 1441 of file pyparsing.py.

1441
1442 def __rne__(self,other):
1443 return not (self == other)
1444

def pyparsing.ParserElement.__ror__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of | operator when left operand is not a ParserElement

Definition at line 1255 of file pyparsing.py.

1255
1256 def __ror__(self, other ):
1257 """Implementation of | operator when left operand is not a ParserElement"""
1258 if isinstance( other, basestring ):
1259 other = Literal( other )
1260 if not isinstance( other, ParserElement ):
1261 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1262 SyntaxWarning, stacklevel=2)
1263 return None
1264 return other | self

def pyparsing.ParserElement.__rsub__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of - operator when left operand is not a ParserElement

Definition at line 1183 of file pyparsing.py.

1183
1184 def __rsub__(self, other ):
1185 """Implementation of - operator when left operand is not a ParserElement"""
1186 if isinstance( other, basestring ):
1187 other = Literal( other )
1188 if not isinstance( other, ParserElement ):
1189 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1190 SyntaxWarning, stacklevel=2)
1191 return None
1192 return other - self

def pyparsing.ParserElement.__rxor__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of ^ operator when left operand is not a ParserElement

Definition at line 1275 of file pyparsing.py.

1275
1276 def __rxor__(self, other ):
1277 """Implementation of ^ operator when left operand is not a ParserElement"""
1278 if isinstance( other, basestring ):
1279 other = Literal( other )
1280 if not isinstance( other, ParserElement ):
1281 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1282 SyntaxWarning, stacklevel=2)
1283 return None
1284 return other ^ self

def pyparsing.ParserElement.__str__ | ( |  | self | ) |

Definition at line 1375 of file pyparsing.py.

1375
1376 def __str__( self ):
1377 return self.name

def pyparsing.ParserElement.__sub__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of - operator, returns And with error stop

Definition at line 1173 of file pyparsing.py.

1173
1174 def __sub__(self, other):
1175 """Implementation of - operator, returns And with error stop"""
1176 if isinstance( other, basestring ):
1177 other = Literal( other )
1178 if not isinstance( other, ParserElement ):
1179 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1180 SyntaxWarning, stacklevel=2)
1181 return None
1182 return And( [ self, And._ErrorStop(), other ] )

def pyparsing.ParserElement.__xor__ | ( |  | self,
|  |  | other
| ) |  |

    Implementation of ^ operator - returns Or

Definition at line 1265 of file pyparsing.py.

1265
1266 def __xor__(self, other ):
1267 """Implementation of ^ operator - returns Or"""
1268 if isinstance( other, basestring ):
1269 other = Literal( other )
1270 if not isinstance( other, ParserElement ):
1271 warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1272 SyntaxWarning, stacklevel=2)
1273 return None
1274 return Or( [ self, other ] )

def pyparsing.ParserElement._normalizeParseActionArgs | ( |  | f | ) |
| private

    Internal method used to decorate parse actions that take fewer than 3 arguments,
       so that all parse actions can be called as f(s,l,t).

Definition at line 747 of file pyparsing.py.

747
748 def _normalizeParseActionArgs( f ):
749 """Internal method used to decorate parse actions that take fewer than 3 arguments,
750 so that all parse actions can be called as f(s,l,t)."""
751 STAR_ARGS = 4
752
753 try:
754 restore = None
755 if isinstance(f,type):
756 restore = f
757 f = f.__init__
758 if not _PY3K:
759 codeObj = f.func_code
760 else:
761 codeObj = f.code
762 if codeObj.co_flags & STAR_ARGS:
763 return f
764 numargs = codeObj.co_argcount
765 if not _PY3K:
766 if hasattr(f,"im_self"):
767 numargs -= 1
768 else:
769 if hasattr(f,"__self__"):
770 numargs -= 1
771 if restore:
772 f = restore
773 except AttributeError:
774 try:
775 if not _PY3K:
776 call_im_func_code = f.__call__.im_func.func_code
777 else:
778 call_im_func_code = f.__code__
779
780 # not a function, must be a callable object, get info from the
781 # im_func binding of its bound __call__ method
782 if call_im_func_code.co_flags & STAR_ARGS:
783 return f
784 numargs = call_im_func_code.co_argcount
785 if not _PY3K:
786 if hasattr(f.__call__,"im_self"):
787 numargs -= 1
788 else:
789 if hasattr(f.__call__,"__self__"):
790 numargs -= 0
791 except AttributeError:
792 if not _PY3K:
793 call_func_code = f.__call__.func_code
794 else:
795 call_func_code = f.__call__.__code__
796 # not a bound method, get info directly from __call__ method
797 if call_func_code.co_flags & STAR_ARGS:
798 return f
799 numargs = call_func_code.co_argcount
800 if not _PY3K:
801 if hasattr(f.__call__,"im_self"):
802 numargs -= 1
803 else:
804 if hasattr(f.__call__,"__self__"):
805 numargs -= 1
806
807
808 #~ print ("adding function %s with %d args" % (f.func_name,numargs))
809 if numargs == 3:
810 return f
811 else:
812 if numargs > 3:
813 def tmp(s,l,t):
814 return f(f.__call__.__self__, s,l,t)
815 if numargs == 2:
816 def tmp(s,l,t):
817 return f(l,t)
818 elif numargs == 1:
819 def tmp(s,l,t):
820 return f(t)
821 else: #~ numargs == 0:
822 def tmp(s,l,t):
823 return f()
824 try:
825 tmp.__name__ = f.__name__
826 except (AttributeError,TypeError):
827 # no need for special handling if attribute doesnt exist
828 pass
829 try:
830 tmp.__doc__ = f.__doc__
831 except (AttributeError,TypeError):
832 # no need for special handling if attribute doesnt exist
833 pass
834 try:
835 tmp.__dict__.update(f.__dict__)
836 except (AttributeError,TypeError):
837 # no need for special handling if attribute doesnt exist
838 pass
return tmp

def pyparsing.ParserElement._parseCache | ( |  | self,
|  |  | instring,
|  |  | loc,
|  |  | doActions = `True`,
|  |  | callPreParse = `True`
| ) |  |
| private

Definition at line 993 of file pyparsing.py.

993
994 def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
995 lookup = (self,instring,loc,callPreParse,doActions)
996 if lookup in ParserElement._exprArgCache:
997 value = ParserElement._exprArgCache[ lookup ]
998 if isinstance(value,Exception):
999 raise value
1000 return value
1001 else:
1002 try:
1003 value = self._parseNoCache( instring, loc, doActions, callPreParse )
1004 ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy())
1005 return value
1006 except ParseBaseException, pe:
1007 ParserElement._exprArgCache[ lookup ] = pe
1008 raise

def pyparsing.ParserElement._parseNoCache | ( |  | self,
|  |  | instring,
|  |  | loc,
|  |  | doActions = `True`,
|  |  | callPreParse = `True`
| ) |  |
| private

Definition at line 913 of file pyparsing.py.

913
914 def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
915 debugging = ( self.debug ) #and doActions )
916
917 if debugging or self.failAction:
918 #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
919 if (self.debugActions[0] ):
920 self.debugActions[0]( instring, loc, self )
921 if callPreParse and self.callPreparse:
922 preloc = self.preParse( instring, loc )
923 else:
924 preloc = loc
925 tokensStart = loc
926 try:
927 try:
928 loc,tokens = self.parseImpl( instring, preloc, doActions )
929 except IndexError:
930 raise ParseException( instring, len(instring), self.errmsg, self )
931 except ParseBaseException, err:
932 #~ print ("Exception raised:", err)
933 if self.debugActions[2]:
934 self.debugActions[2]( instring, tokensStart, self, err )
935 if self.failAction:
936 self.failAction( instring, tokensStart, self, err )
937 raise
938 else:
939 if callPreParse and self.callPreparse:
940 preloc = self.preParse( instring, loc )
941 else:
942 preloc = loc
943 tokensStart = loc
944 if self.mayIndexError or loc >= len(instring):
945 try:
946 loc,tokens = self.parseImpl( instring, preloc, doActions )
947 except IndexError:
948 raise ParseException( instring, len(instring), self.errmsg, self )
949 else:
950 loc,tokens = self.parseImpl( instring, preloc, doActions )
951
952 tokens = self.postParse( instring, loc, tokens )
953
954 retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
955 if self.parseAction and (doActions or self.callDuringTry):
956 if debugging:
957 try:
958 for fn in self.parseAction:
959 tokens = fn( instring, tokensStart, retTokens )
960 if tokens is not None:
961 retTokens = ParseResults( tokens,
962 self.resultsName,
963 asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
964 modal=self.modalResults )
965 except ParseBaseException, err:
966 #~ print "Exception raised in user parse action:", err
967 if (self.debugActions[2] ):
968 self.debugActions[2]( instring, tokensStart, self, err )
969 raise
970 else:
971 for fn in self.parseAction:
972 tokens = fn( instring, tokensStart, retTokens )
973 if tokens is not None:
974 retTokens = ParseResults( tokens,
975 self.resultsName,
976 asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
977 modal=self.modalResults )
978
979 if debugging:
980 #~ print ("Matched",self,"->",retTokens.asList())
981 if (self.debugActions[1] ):
982 self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
983
984 return loc, retTokens

def pyparsing.ParserElement._skipIgnorables | ( |  | self,
|  |  | instring,
|  |  | loc
| ) |  |
| private

Definition at line 881 of file pyparsing.py.

881
882 def _skipIgnorables( self, instring, loc ):
883 exprsFound = True
884 while exprsFound:
885 exprsFound = False
886 for e in self.ignoreExprs:
887 try:
888 while 1:
889 loc,dummy = e._parse( instring, loc )
890 exprsFound = True
891 except ParseException:
892 pass
893 return loc

def pyparsing.ParserElement.addParseAction | ( |  | self,
|  |  | fns,
|  |  | kwargs
| ) |  |

    Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.

Definition at line 862 of file pyparsing.py.

862
863 def addParseAction( self, *fns, **kwargs ):
864 """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
865 self.parseAction += list(map(self._normalizeParseActionArgs, list(fns)))
866 self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
867 return self

def pyparsing.ParserElement.checkRecursion | ( |  | self,
|  |  | parseElementList
| ) |  |

Definition at line 1386 of file pyparsing.py.

1386
1387 def checkRecursion( self, parseElementList ):
1388 pass

def pyparsing.ParserElement.copy | ( |  | self | ) |

    Make a copy of this ParserElement.  Useful for defining different parse actions
       for the same parsing pattern, using copies of the original parse element.

Definition at line 699 of file pyparsing.py.

699
700 def copy( self ):
701 """Make a copy of this ParserElement. Useful for defining different parse actions
702 for the same parsing pattern, using copies of the original parse element."""
703 cpy = copy.copy( self )
704 cpy.parseAction = self.parseAction[:]
705 cpy.ignoreExprs = self.ignoreExprs[:]
706 if self.copyDefaultWhiteChars:
707 cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
708 return cpy

def pyparsing.ParserElement.enablePackrat | ( |  | ) |

    Enables "packrat" parsing, which adds memoizing to the parsing logic.
       Repeated parse attempts at the same string location (which happens
       often in many complex grammars) can immediately return a cached value,
       instead of re-executing parsing/validating code.  Memoizing is done of
       both valid results and parsing exceptions.

       This speedup may break existing programs that use parse actions that
       have side-effects.  For this reason, packrat parsing is disabled when
       you first import pyparsing.  To activate the packrat feature, your
       program must call the class method ParserElement.enablePackrat().  If
       your program uses psyco to "compile as you go", you must call
       enablePackrat before calling psyco.full().  If you do not do this,
       Python will crash.  For best results, call enablePackrat() immediately
       after importing pyparsing.

Definition at line 1018 of file pyparsing.py.

1018
1019 def enablePackrat():
1020 """Enables "packrat" parsing, which adds memoizing to the parsing logic.
1021 Repeated parse attempts at the same string location (which happens
1022 often in many complex grammars) can immediately return a cached value,
1023 instead of re-executing parsing/validating code. Memoizing is done of
1024 both valid results and parsing exceptions.
1025
1026 This speedup may break existing programs that use parse actions that
1027 have side-effects. For this reason, packrat parsing is disabled when
1028 you first import pyparsing. To activate the packrat feature, your
1029 program must call the class method ParserElement.enablePackrat(). If
1030 your program uses psyco to "compile as you go", you must call
1031 enablePackrat before calling psyco.full(). If you do not do this,
1032 Python will crash. For best results, call enablePackrat() immediately
1033 after importing pyparsing.
1034 """
1035 if not ParserElement._packratEnabled:
1036 ParserElement._packratEnabled = True
ParserElement._parse = ParserElement._parseCache

def pyparsing.ParserElement.getException | ( |  | self | ) |

Definition at line 1410 of file pyparsing.py.

1410
1411 def getException(self):
1412 return ParseException("",0,self.errmsg,self)

def pyparsing.ParserElement.ignore | ( |  | self,
|  |  | other
| ) |  |

    Define expression to be ignored (e.g., comments) while doing pattern
       matching; may be called repeatedly, to define multiple comment or other
       ignorable patterns.

Definition at line 1346 of file pyparsing.py.

1346
1347 def ignore( self, other ):
1348 """Define expression to be ignored (e.g., comments) while doing pattern
1349 matching; may be called repeatedly, to define multiple comment or other
1350 ignorable patterns.
1351 """
1352 if isinstance( other, Suppress ):
1353 if other not in self.ignoreExprs:
1354 self.ignoreExprs.append( other )
1355 else:
1356 self.ignoreExprs.append( Suppress( other ) )
1357 return self

def pyparsing.ParserElement.leaveWhitespace | ( |  | self | ) |

    Disables the skipping of whitespace before matching the characters in the
       ParserElement's defined pattern.  This is normally only used internally by
       the pyparsing module, but may be needed in some whitespace-sensitive grammars.

Definition at line 1323 of file pyparsing.py.

1323
1324 def leaveWhitespace( self ):
1325 """Disables the skipping of whitespace before matching the characters in the
1326 ParserElement's defined pattern. This is normally only used internally by
1327 the pyparsing module, but may be needed in some whitespace-sensitive grammars.
1328 """
1329 self.skipWhitespace = False
1330 return self

def pyparsing.ParserElement.parseFile | ( |  | self,
|  |  | file_or_filename,
|  |  | parseAll = `False`
| ) |  |

    Execute the parse expression on the given file or filename.
       If a filename is specified (instead of a file object),
       the entire file is opened, read, and closed before parsing.

Definition at line 1393 of file pyparsing.py.

1393
1394 def parseFile( self, file_or_filename, parseAll=False ):
1395 """Execute the parse expression on the given file or filename.
1396 If a filename is specified (instead of a file object),
1397 the entire file is opened, read, and closed before parsing.
1398 """
1399 try:
1400 file_contents = file_or_filename.read()
1401 except AttributeError:
1402 f = open(file_or_filename, "rb")
1403 file_contents = f.read()
1404 f.close()
1405 try:
1406 return self.parseString(file_contents, parseAll)
1407 except ParseBaseException, exc:
1408 # catch and re-raise exception from here, clears out pyparsing internal stack trace
1409 raise exc

def pyparsing.ParserElement.parseImpl | ( |  | self,
|  |  | instring,
|  |  | loc,
|  |  | doActions = `True`
| ) |  |

Definition at line 906 of file pyparsing.py.

906
907 def parseImpl( self, instring, loc, doActions=True ):
908 return loc, []

def pyparsing.ParserElement.parseString | ( |  | self,
|  |  | instring,
|  |  | parseAll = `False`
| ) |  |

    Execute the parse expression with the given string.
       This is the main interface to the client code, once the complete
       expression has been built.

       If you want the grammar to require that the entire input string be
       successfully parsed, then set parseAll to True (equivalent to ending
       the grammar with StringEnd()).

       Note: parseString implicitly calls expandtabs() on the input string,
       in order to report proper column numbers in parse actions.
       If the input string contains tabs and
       the grammar uses parse actions that use the loc argument to index into the
       string being parsed, you can ensure you have a consistent view of the input
       string by:
        - calling parseWithTabs on your grammar before calling parseString
          (see L{I{parseWithTabs}<parseWithTabs>})
        - define your parse action using the full (s,loc,toks) signature, and
          reference the input string using the parse action's s argument
        - explictly expand the tabs in your input string before calling
          parseString

Definition at line 1039 of file pyparsing.py.

1039
1040 def parseString( self, instring, parseAll=False ):
1041 """Execute the parse expression with the given string.
1042 This is the main interface to the client code, once the complete
1043 expression has been built.
1044
1045 If you want the grammar to require that the entire input string be
1046 successfully parsed, then set parseAll to True (equivalent to ending
1047 the grammar with StringEnd()).
1048
1049 Note: parseString implicitly calls expandtabs() on the input string,
1050 in order to report proper column numbers in parse actions.
1051 If the input string contains tabs and
1052 the grammar uses parse actions that use the loc argument to index into the
1053 string being parsed, you can ensure you have a consistent view of the input
1054 string by:
1055 - calling parseWithTabs on your grammar before calling parseString
1056 (see L{I{parseWithTabs}<parseWithTabs>})
1057 - define your parse action using the full (s,loc,toks) signature, and
1058 reference the input string using the parse action's s argument
1059 - explictly expand the tabs in your input string before calling
1060 parseString
1061 """
1062 ParserElement.resetCache()
1063 if not self.streamlined:
1064 self.streamline()
1065 #~ self.saveAsList = True
1066 for e in self.ignoreExprs:
1067 e.streamline()
1068 if not self.keepTabs:
1069 instring = instring.expandtabs()
1070 try:
1071 loc, tokens = self._parse( instring, 0 )
1072 if parseAll:
1073 loc = self.preParse( instring, loc )
1074 StringEnd()._parse( instring, loc )
1075 except ParseBaseException, exc:
1076 # catch and re-raise exception from here, clears out pyparsing internal stack trace
1077 raise exc
1078 else:
1079 return tokens

def pyparsing.ParserElement.parseWithTabs | ( |  | self | ) |

    Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
       Must be called before parseString when the input grammar contains elements that
       match <TAB> characters.

Definition at line 1339 of file pyparsing.py.

1339
1340 def parseWithTabs( self ):
1341 """Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
1342 Must be called before parseString when the input grammar contains elements that
1343 match <TAB> characters."""
1344 self.keepTabs = True
1345 return self

def pyparsing.ParserElement.postParse | ( |  | self,
|  |  | instring,
|  |  | loc,
|  |  | tokenlist
| ) |  |

Definition at line 909 of file pyparsing.py.

909
910 def postParse( self, instring, loc, tokenlist ):
911 return tokenlist

def pyparsing.ParserElement.preParse | ( |  | self,
|  |  | instring,
|  |  | loc
| ) |  |

Definition at line 894 of file pyparsing.py.

894
895 def preParse( self, instring, loc ):
896 if self.ignoreExprs:
897 loc = self._skipIgnorables( instring, loc )
898
899 if self.skipWhitespace:
900 wt = self.whiteChars
901 instrlen = len(instring)
902 while loc < instrlen and instring[loc] in wt:
903 loc += 1
904
905 return loc

def pyparsing.ParserElement.resetCache | ( |  | ) |

Definition at line 1013 of file pyparsing.py.

1013
1014 def resetCache():
ParserElement._exprArgCache.clear()

def pyparsing.ParserElement.scanString | ( |  | self,
|  |  | instring,
|  |  | maxMatches = `_MAX_INT`
| ) |  |

    Scan the input string for expression matches.  Each match will return the
       matching tokens, start location, and end location.  May be called with optional
       maxMatches argument, to clip scanning after 'n' matches are found.

       Note that the start and end locations are reported relative to the string
       being parsed.  See L{I{parseString}<parseString>} for more information on parsing
       strings with embedded tabs.

Definition at line 1080 of file pyparsing.py.

1080
1081 def scanString( self, instring, maxMatches=_MAX_INT ):
1082 """Scan the input string for expression matches. Each match will return the
1083 matching tokens, start location, and end location. May be called with optional
1084 maxMatches argument, to clip scanning after 'n' matches are found.
1085
1086 Note that the start and end locations are reported relative to the string
1087 being parsed. See L{I{parseString}<parseString>} for more information on parsing
1088 strings with embedded tabs."""
1089 if not self.streamlined:
1090 self.streamline()
1091 for e in self.ignoreExprs:
1092 e.streamline()
1093
1094 if not self.keepTabs:
1095 instring = _ustr(instring).expandtabs()
1096 instrlen = len(instring)
1097 loc = 0
1098 preparseFn = self.preParse
1099 parseFn = self._parse
1100 ParserElement.resetCache()
1101 matches = 0
1102 try:
1103 while loc <= instrlen and matches < maxMatches:
1104 try:
1105 preloc = preparseFn( instring, loc )
1106 nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
1107 except ParseException:
1108 loc = preloc+1
1109 else:
1110 matches += 1
1111 yield tokens, preloc, nextLoc
1112 loc = nextLoc
1113 except ParseBaseException, pe:
1114 raise pe

def pyparsing.ParserElement.searchString | ( |  | self,
|  |  | instring,
|  |  | maxMatches = `_MAX_INT`
| ) |  |

    Another extension to scanString, simplifying the access to the tokens found
       to match the given parse expression.  May be called with optional
       maxMatches argument, to clip searching after 'n' matches are found.

Definition at line 1143 of file pyparsing.py.

1143
1144 def searchString( self, instring, maxMatches=_MAX_INT ):
1145 """Another extension to scanString, simplifying the access to the tokens found
1146 to match the given parse expression. May be called with optional
1147 maxMatches argument, to clip searching after 'n' matches are found.
1148 """
1149 try:
1150 return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
1151 except ParseBaseException, pe:
1152 raise pe

def pyparsing.ParserElement.setBreak | ( |  | self,
|  |  | breakFlag = `True`
| ) |  |

    Method to invoke the Python pdb debugger when this element is
       about to be parsed. Set breakFlag to True to enable, False to
       disable.

Definition at line 729 of file pyparsing.py.

729
730 def setBreak(self,breakFlag = True):
731 """Method to invoke the Python pdb debugger when this element is
732 about to be parsed. Set breakFlag to True to enable, False to
733 disable.
734 """
735 if breakFlag:
736 _parseMethod = self._parse
737 def breaker(instring, loc, doActions=True, callPreParse=True):
738 import pdb
739 pdb.set_trace()
740 return _parseMethod( instring, loc, doActions, callPreParse )
741 breaker._originalParseMethod = _parseMethod
742 self._parse = breaker
743 else:
744 if hasattr(self._parse,"_originalParseMethod"):
745 self._parse = self._parse._originalParseMethod
746 return self

def pyparsing.ParserElement.setDebug | ( |  | self,
|  |  | flag = `True`
| ) |  |

    Enable display of debugging messages while doing pattern matching.
       Set flag to True to enable, False to disable.

Definition at line 1366 of file pyparsing.py.

1366
1367 def setDebug( self, flag=True ):
1368 """Enable display of debugging messages while doing pattern matching.
1369 Set flag to True to enable, False to disable."""
1370 if flag:
1371 self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
1372 else:
1373 self.debug = False
1374 return self

def pyparsing.ParserElement.setDebugActions | ( |  | self,
|  |  | startAction,
|  |  | successAction,
|  |  | exceptionAction
| ) |  |

    Enable display of debugging messages while doing pattern matching.

Definition at line 1358 of file pyparsing.py.

1358
1359 def setDebugActions( self, startAction, successAction, exceptionAction ):
1360 """Enable display of debugging messages while doing pattern matching."""
1361 self.debugActions = (startAction or _defaultStartDebugAction,
1362 successAction or _defaultSuccessDebugAction,
1363 exceptionAction or _defaultExceptionDebugAction)
1364 self.debug = True
1365 return self

def pyparsing.ParserElement.setDefaultWhitespaceChars | ( |  | chars | ) |

    Overrides the default whitespace chars

Definition at line 670 of file pyparsing.py.

670
671 def setDefaultWhitespaceChars( chars ):
672 """Overrides the default whitespace chars
673 """
ParserElement.DEFAULT_WHITE_CHARS = chars

def pyparsing.ParserElement.setFailAction | ( |  | self,
|  |  | fn
| ) |  |

    Define action to perform if parsing fails at this expression.
       Fail acton fn is a callable function that takes the arguments
       fn(s,loc,expr,err) where:
        - s = string being parsed
        - loc = location where expression match was attempted and failed
        - expr = the parse expression that failed
        - err = the exception thrown
       The function returns no value.  It may throw ParseFatalException
       if it is desired to stop parsing immediately.

Definition at line 868 of file pyparsing.py.

868
869 def setFailAction( self, fn ):
870 """Define action to perform if parsing fails at this expression.
871 Fail acton fn is a callable function that takes the arguments
872 fn(s,loc,expr,err) where:
873 - s = string being parsed
874 - loc = location where expression match was attempted and failed
875 - expr = the parse expression that failed
876 - err = the exception thrown
877 The function returns no value. It may throw ParseFatalException
878 if it is desired to stop parsing immediately."""
879 self.failAction = fn
880 return self

def pyparsing.ParserElement.setName | ( |  | self,
|  |  | name
| ) |  |

    Define name for this expression, for use in debugging.

Definition at line 709 of file pyparsing.py.

709
710 def setName( self, name ):
711 """Define name for this expression, for use in debugging."""
712 self.name = name
713 self.errmsg = "Expected " + self.name
714 if hasattr(self,"exception"):
715 self.exception.msg = self.errmsg
716 return self

def pyparsing.ParserElement.setParseAction | ( |  | self,
|  |  | fns,
|  |  | kwargs
| ) |  |

    Define action to perform when successfully matching parse element definition.
       Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
       fn(loc,toks), fn(toks), or just fn(), where:
        - s   = the original string being parsed (see note below)
        - loc = the location of the matching substring
        - toks = a list of the matched tokens, packaged as a ParseResults object
       If the functions in fns modify the tokens, they can return them as the return
       value from fn, and the modified list of tokens will replace the original.
       Otherwise, fn does not need to return any value.

       Note: the default parsing behavior is to expand tabs in the input string
       before starting the parsing process.  See L{I{parseString}<parseString>} for more information
       on parsing strings containing <TAB>s, and suggested methods to maintain a
       consistent view of the parsed string, the parse location, and line and column
       positions within the parsed string.

Definition at line 841 of file pyparsing.py.

841
842 def setParseAction( self, *fns, **kwargs ):
843 """Define action to perform when successfully matching parse element definition.
844 Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks),
845 fn(loc,toks), fn(toks), or just fn(), where:
846 - s = the original string being parsed (see note below)
847 - loc = the location of the matching substring
848 - toks = a list of the matched tokens, packaged as a ParseResults object
849 If the functions in fns modify the tokens, they can return them as the return
850 value from fn, and the modified list of tokens will replace the original.
851 Otherwise, fn does not need to return any value.
852
853 Note: the default parsing behavior is to expand tabs in the input string
854 before starting the parsing process. See L{I{parseString}<parseString>} for more information
855 on parsing strings containing <TAB>s, and suggested methods to maintain a
856 consistent view of the parsed string, the parse location, and line and column
857 positions within the parsed string.
858 """
859 self.parseAction = list(map(self._normalizeParseActionArgs, list(fns)))
860 self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
861 return self

def pyparsing.ParserElement.setResultsName | ( |  | self,
|  |  | name,
|  |  | listAllMatches = `False`
| ) |  |

    Define name for referencing matching tokens as a nested attribute
       of the returned parse results.
       NOTE: this returns a *copy* of the original ParserElement object;
       this is so that the client can define a basic element, such as an
       integer, and reference it in multiple places with different names.

Definition at line 717 of file pyparsing.py.

717
718 def setResultsName( self, name, listAllMatches=False ):
719 """Define name for referencing matching tokens as a nested attribute
720 of the returned parse results.
721 NOTE: this returns a *copy* of the original ParserElement object;
722 this is so that the client can define a basic element, such as an
723 integer, and reference it in multiple places with different names.
724 """
725 newself = self.copy()
726 newself.resultsName = name
727 newself.modalResults = not listAllMatches
728 return newself

def pyparsing.ParserElement.setWhitespaceChars | ( |  | self,
|  |  | chars
| ) |  |

    Overrides the default whitespace chars

Definition at line 1331 of file pyparsing.py.

1331
1332 def setWhitespaceChars( self, chars ):
1333 """Overrides the default whitespace chars
1334 """
1335 self.skipWhitespace = True
1336 self.whiteChars = chars
1337 self.copyDefaultWhiteChars = False
1338 return self

def pyparsing.ParserElement.streamline | ( |  | self | ) |

Definition at line 1381 of file pyparsing.py.

1381
1382 def streamline( self ):
1383 self.streamlined = True
1384 self.strRepr = None
1385 return self

def pyparsing.ParserElement.suppress | ( |  | self | ) |

    Suppresses the output of this ParserElement; useful to keep punctuation from
       cluttering up returned output.

Definition at line 1317 of file pyparsing.py.

1317
1318 def suppress( self ):
1319 """Suppresses the output of this ParserElement; useful to keep punctuation from
1320 cluttering up returned output.
1321 """
1322 return Suppress( self )

def pyparsing.ParserElement.transformString | ( |  | self,
|  |  | instring
| ) |  |

    Extension to scanString, to modify matching text with modified tokens that may
       be returned from a parse action.  To use transformString, define a grammar and
       attach a parse action to it that modifies the returned token list.
       Invoking transformString() on a target string will then scan for matches,
       and replace the matched text patterns according to the logic in the parse
       action.  transformString() returns the resulting transformed string.

Definition at line 1115 of file pyparsing.py.

1115
1116 def transformString( self, instring ):
1117 """Extension to scanString, to modify matching text with modified tokens that may
1118 be returned from a parse action. To use transformString, define a grammar and
1119 attach a parse action to it that modifies the returned token list.
1120 Invoking transformString() on a target string will then scan for matches,
1121 and replace the matched text patterns according to the logic in the parse
1122 action. transformString() returns the resulting transformed string."""
1123 out = []
1124 lastE = 0
1125 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
1126 # keep string locs straight between transformString and scanString
1127 self.keepTabs = True
1128 try:
1129 for t,s,e in self.scanString( instring ):
1130 out.append( instring[lastE:s] )
1131 if t:
1132 if isinstance(t,ParseResults):
1133 out += t.asList()
1134 elif isinstance(t,list):
1135 out += t
1136 else:
1137 out.append(t)
1138 lastE = e
1139 out.append(instring[lastE:])
1140 return "".join(map(_ustr,out))
1141 except ParseBaseException, pe:
1142 raise pe

def pyparsing.ParserElement.tryParse | ( |  | self,
|  |  | instring,
|  |  | loc
| ) |  |

Definition at line 985 of file pyparsing.py.

985
986 def tryParse( self, instring, loc ):
987 try:
988 return self._parse( instring, loc, doActions=False )[0]
989 except ParseFatalException:
990 raise ParseException( instring, loc, self.errmsg, self)

def pyparsing.ParserElement.validate | ( |  | self,
|  |  | validateTrace = `[]`
| ) |  |

    Check defined expressions for valid structure, check for infinite recursive definitions.

Definition at line 1389 of file pyparsing.py.

1389
1390 def validate( self, validateTrace=[] ):
1391 """Check defined expressions for valid structure, check for infinite recursive definitions."""
1392 self.checkRecursion( [] )

## Member Data Documentation

pyparsing.ParserElement.__dict__
| private

Definition at line 1422 of file pyparsing.py.

dictionary pyparsing.ParserElement._exprArgCache {}
| static private

Definition at line 1012 of file pyparsing.py.

tuple pyparsing.ParserElement._normalizeParseActionArgs staticmethod(_normalizeParseActionArgs)
| static private

Definition at line 839 of file pyparsing.py.

pyparsing.ParserElement._packratEnabled False
| static private

Definition at line 1017 of file pyparsing.py.

pyparsing.ParserElement._parse _parseNoCache
| static private

Definition at line 1009 of file pyparsing.py.

pyparsing.ParserElement.callDuringTry

Definition at line 697 of file pyparsing.py.

pyparsing.ParserElement.callPreparse

Definition at line 696 of file pyparsing.py.

pyparsing.ParserElement.copyDefaultWhiteChars

Definition at line 685 of file pyparsing.py.

pyparsing.ParserElement.debug

Definition at line 689 of file pyparsing.py.

pyparsing.ParserElement.debugActions

Definition at line 694 of file pyparsing.py.

string pyparsing.ParserElement.DEFAULT_WHITE_CHARS " \n\t\r"
| static

Definition at line 668 of file pyparsing.py.

tuple pyparsing.ParserElement.enablePackrat staticmethod(enablePackrat)
| static

Definition at line 1037 of file pyparsing.py.

pyparsing.ParserElement.errmsg

Definition at line 692 of file pyparsing.py.

pyparsing.ParserElement.failAction

Definition at line 678 of file pyparsing.py.

pyparsing.ParserElement.ignoreExprs

Definition at line 688 of file pyparsing.py.

pyparsing.ParserElement.keepTabs

Definition at line 687 of file pyparsing.py.

pyparsing.ParserElement.mayIndexError

Definition at line 691 of file pyparsing.py.

pyparsing.ParserElement.mayReturnEmpty

Definition at line 686 of file pyparsing.py.

pyparsing.ParserElement.modalResults

Definition at line 693 of file pyparsing.py.

pyparsing.ParserElement.myException

Definition at line 1415 of file pyparsing.py.

pyparsing.ParserElement.name

Definition at line 711 of file pyparsing.py.

pyparsing.ParserElement.parseAction

Definition at line 677 of file pyparsing.py.

pyparsing.ParserElement.re

Definition at line 695 of file pyparsing.py.

tuple pyparsing.ParserElement.resetCache staticmethod(resetCache)
| static

Definition at line 1015 of file pyparsing.py.

pyparsing.ParserElement.resultsName

Definition at line 681 of file pyparsing.py.

pyparsing.ParserElement.saveAsList

Definition at line 682 of file pyparsing.py.

tuple pyparsing.ParserElement.setDefaultWhitespaceChars staticmethod(setDefaultWhitespaceChars)
| static

Definition at line 674 of file pyparsing.py.

pyparsing.ParserElement.skipWhitespace

Definition at line 683 of file pyparsing.py.

pyparsing.ParserElement.streamlined

Definition at line 690 of file pyparsing.py.

pyparsing.ParserElement.strRepr

Definition at line 680 of file pyparsing.py.

pyparsing.ParserElement.whiteChars

Definition at line 684 of file pyparsing.py.

The documentation for this class was generated from the following file:

- /afs/cern.ch/sw/Gaudi/releases/GAUDI/GAUDI_v25r0/cmake/cmt2cmake/pyparsing.py