desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'For artists in an axes, if the yaxis has units support, convert *y* using yaxis unit type'
def convert_yunits(self, y):
ax = getattr(self, 'axes', None) if ((ax is None) or (ax.yaxis is None)): return y return ax.yaxis.convert_units(y)
'Set the :class:`~matplotlib.axes.Axes` instance in which the artist resides, if any. ACCEPTS: an :class:`~matplotlib.axes.Axes` instance'
def set_axes(self, axes):
self.axes = axes
'Return the :class:`~matplotlib.axes.Axes` instance the artist resides in, or *None*'
def get_axes(self):
return self.axes
'Adds a callback function that will be called whenever one of the :class:`Artist`\'s properties changes. Returns an *id* that is useful for removing the callback with :meth:`remove_callback` later.'
def add_callback(self, func):
oid = self._oid self._propobservers[oid] = func self._oid += 1 return oid
'Remove a callback based on its *id*. .. seealso:: :meth:`add_callback`'
def remove_callback(self, oid):
try: del self._propobservers[oid] except KeyError: pass
'Fire an event when property changed, calling all of the registered callbacks.'
def pchanged(self):
for (oid, func) in self._propobservers.items(): func(self)
'Returns *True* if :class:`Artist` has a transform explicitly set.'
def is_transform_set(self):
return self._transformSet
'Set the :class:`~matplotlib.transforms.Transform` instance used by this artist. ACCEPTS: :class:`~matplotlib.transforms.Transform` instance'
def set_transform(self, t):
self._transform = t self._transformSet = True self.pchanged()
'Return the :class:`~matplotlib.transforms.Transform` instance used by this artist.'
def get_transform(self):
if (self._transform is None): self._transform = IdentityTransform() return self._transform
'List the children of the artist which contain the mouse event *event*.'
def hitlist(self, event):
import traceback L = [] try: (hascursor, info) = self.contains(event) if hascursor: L.append(self) except: traceback.print_exc() print 'while checking', self.__class__ for a in self.get_children(): L.extend(a.hitlist(event)) return L
'Return a list of the child :class:`Artist`s this :class:`Artist` contains.'
def get_children(self):
return []
'Test whether the artist contains the mouse event. Returns the truth value and a dictionary of artist specific details of selection, such as which points are contained in the pick radius. See individual artists for details.'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) warnings.warn(("'%s' needs 'contains' method" % self.__class__.__name__)) return (False, {})
'Replace the contains test used by this artist. The new picker should be a callable function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) If the mouse event is over the artist, return *hit* = *True* and *props* is a dictionary of properties you want returned wi...
def set_contains(self, picker):
self._contains = picker
'Return the _contains test used by the artist, or *None* for default.'
def get_contains(self):
return self._contains
'Return *True* if :class:`Artist` is pickable.'
def pickable(self):
return ((self.figure is not None) and (self.figure.canvas is not None) and (self._picker is not None))
'call signature:: pick(mouseevent) each child artist will fire a pick event if *mouseevent* is over the artist and the artist has picker set'
def pick(self, mouseevent):
if self.pickable(): picker = self.get_picker() if callable(picker): (inside, prop) = picker(self, mouseevent) else: (inside, prop) = self.contains(mouseevent) if inside: self.figure.canvas.pick_event(mouseevent, self, **prop) for a in self.get_...
'Set the epsilon for picking used by this artist *picker* can be one of the following: * *None*: picking is disabled for this artist (default) * A boolean: if *True* then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist * A float: if picker is a number it is interprete...
def set_picker(self, picker):
self._picker = picker
'Return the picker object used by this artist'
def get_picker(self):
return self._picker
'Returns True if the artist is assigned to a :class:`~matplotlib.figure.Figure`.'
def is_figure_set(self):
return (self.figure is not None)
'Returns the url'
def get_url(self):
return self._url
'Sets the url for the artist'
def set_url(self, url):
self._url = url
'Returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg backends.'
def get_snap(self):
return self._snap
'Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg backends.'
def set_snap(self, snap):
self._snap = snap
'Return the :class:`~matplotlib.figure.Figure` instance the artist belongs to.'
def get_figure(self):
return self.figure
'Set the :class:`~matplotlib.figure.Figure` instance the artist belongs to. ACCEPTS: a :class:`matplotlib.figure.Figure` instance'
def set_figure(self, fig):
self.figure = fig self.pchanged()
'Set the artist\'s clip :class:`~matplotlib.transforms.Bbox`. ACCEPTS: a :class:`matplotlib.transforms.Bbox` instance'
def set_clip_box(self, clipbox):
self.clipbox = clipbox self.pchanged()
'Set the artist\'s clip path, which may be: * a :class:`~matplotlib.patches.Patch` (or subclass) instance * a :class:`~matplotlib.path.Path` instance, in which case an optional :class:`~matplotlib.transforms.Transform` instance may be provided, which will be applied to the path before using it for clipping. * *None*, t...
def set_clip_path(self, path, transform=None):
from patches import Patch, Rectangle success = False if (transform is None): if isinstance(path, Rectangle): self.clipbox = TransformedBbox(Bbox.unit(), path.get_transform()) self._clippath = None success = True elif isinstance(path, Patch): se...
'Return the alpha value used for blending - not supported on all backends'
def get_alpha(self):
return self._alpha
'Return the artist\'s visiblity'
def get_visible(self):
return self._visible
'Return the artist\'s animated state'
def get_animated(self):
return self._animated
'Return whether artist uses clipping'
def get_clip_on(self):
return self._clipon
'Return artist clipbox'
def get_clip_box(self):
return self.clipbox
'Return artist clip path'
def get_clip_path(self):
return self._clippath
'Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.'
def get_transformed_clip_path_and_affine(self):
if (self._clippath is not None): return self._clippath.get_transformed_path_and_affine() return (None, None)
'Set whether artist uses clipping. ACCEPTS: [True | False]'
def set_clip_on(self, b):
self._clipon = b self.pchanged()
'Set the clip properly for the gc'
def _set_gc_clip(self, gc):
if self._clipon: if (self.clipbox is not None): gc.set_clip_rectangle(self.clipbox) gc.set_clip_path(self._clippath) else: gc.set_clip_rectangle(None) gc.set_clip_path(None)
'Derived classes drawing method'
def draw(self, renderer, *args, **kwargs):
if (not self.get_visible()): return
'Set the alpha value used for blending - not supported on all backends ACCEPTS: float (0.0 transparent through 1.0 opaque)'
def set_alpha(self, alpha):
self._alpha = alpha self.pchanged()
'Set Level of Detail on or off. If on, the artists may examine things like the pixel width of the axes and draw a subset of their contents accordingly ACCEPTS: [True | False]'
def set_lod(self, on):
self._lod = on self.pchanged()
'Set the artist\'s visiblity. ACCEPTS: [True | False]'
def set_visible(self, b):
self._visible = b self.pchanged()
'Set the artist\'s animation state. ACCEPTS: [True | False]'
def set_animated(self, b):
self._animated = b self.pchanged()
'Update the properties of this :class:`Artist` from the dictionary *prop*.'
def update(self, props):
store = self.eventson self.eventson = False changed = False for (k, v) in props.items(): func = getattr(self, ('set_' + k), None) if ((func is None) or (not callable(func))): raise AttributeError(('Unknown property %s' % k)) func(v) changed = True se...
'Get the label used for this artist in the legend.'
def get_label(self):
return self._label
'Set the label to *s* for auto legend. ACCEPTS: any string'
def set_label(self, s):
self._label = s self.pchanged()
'Return the :class:`Artist`\'s zorder.'
def get_zorder(self):
return self.zorder
'Set the zorder for the artist. Artists with lower zorder values are drawn first. ACCEPTS: any number'
def set_zorder(self, level):
self.zorder = level self.pchanged()
'Copy properties from *other* to *self*.'
def update_from(self, other):
self._transform = other._transform self._transformSet = other._transformSet self._visible = other._visible self._alpha = other._alpha self.clipbox = other.clipbox self._clipon = other._clipon self._clippath = other._clippath self._lod = other._lod self._label = other._label self....
'A tkstyle set command, pass *kwargs* to set properties'
def set(self, **kwargs):
ret = [] for (k, v) in kwargs.items(): k = k.lower() funcName = ('set_%s' % k) func = getattr(self, funcName) ret.extend([func(v)]) return ret
'pyplot signature: findobj(o=gcf(), match=None) Recursively find all :class:matplotlib.artist.Artist instances contained in self. *match* can be - None: return all objects contained in artist (including artist) - function with signature ``boolean = match(artist)`` used to filter matches - class instance: eg Line2D. On...
def findobj(self, match=None):
if (match is None): def matchfunc(x): return True elif cbook.issubclass_safe(match, Artist): def matchfunc(x): return isinstance(x, match) elif callable(match): matchfunc = match else: raise ValueError('match must be None, an matplot...
'Initialize the artist inspector with an :class:`~matplotlib.artist.Artist` or sequence of :class:`Artists`. If a sequence is used, we assume it is a homogeneous sequence (all :class:`Artists` are of the same type) and it is your responsibility to make sure this is so.'
def __init__(self, o):
if (cbook.iterable(o) and len(o)): o = o[0] self.oorig = o if (not isinstance(o, type)): o = type(o) self.o = o self.aliasd = self.get_aliases()
'Get a dict mapping *fullname* -> *alias* for each *alias* in the :class:`~matplotlib.artist.ArtistInspector`. Eg., for lines:: {\'markerfacecolor\': \'mfc\', \'linewidth\' : \'lw\','
def get_aliases(self):
names = [name for name in dir(self.o) if ((name.startswith('set_') or name.startswith('get_')) and callable(getattr(self.o, name)))] aliases = {} for name in names: func = getattr(self.o, name) if (not self.is_alias(func)): continue docstring = func.__doc__ fullna...
'Get the legal arguments for the setter associated with *attr*. This is done by querying the docstring of the function *set_attr* for a line that begins with ACCEPTS: Eg., for a line linestyle, return [ \'-\' | \'--\' | \'-.\' | \':\' | \'steps\' | \'None\' ]'
def get_valid_values(self, attr):
name = ('set_%s' % attr) if (not hasattr(self.o, name)): raise AttributeError(('%s has no function %s' % (self.o, name))) func = getattr(self.o, name) docstring = func.__doc__ if (docstring is None): return 'unknown' if docstring.startswith('alias for '): ...
'Get the attribute strings and a full path to where the setter is defined for all setters in an object.'
def _get_setters_and_targets(self):
setters = [] for name in dir(self.o): if (not name.startswith('set_')): continue o = getattr(self.o, name) if (not callable(o)): continue func = o if self.is_alias(func): continue source_class = ((self.o.__module__ + '.') + self...
'Get the attribute strings with setters for object. Eg., for a line, return ``[\'markerfacecolor\', \'linewidth\', ....]``.'
def get_setters(self):
return [prop for (prop, target) in self._get_setters_and_targets()]
'Return *True* if method object *o* is an alias for another function.'
def is_alias(self, o):
ds = o.__doc__ if (ds is None): return False return ds.startswith('alias for ')
'return \'PROPNAME or alias\' if *s* has an alias, else return PROPNAME. E.g. for the line markerfacecolor property, which has an alias, return \'markerfacecolor or mfc\' and for the transform property, which does not, return \'transform\''
def aliased_name(self, s):
if (s in self.aliasd): return (s + ''.join([(' or %s' % x) for x in self.aliasd[s].keys()])) else: return s
'return \'PROPNAME or alias\' if *s* has an alias, else return PROPNAME formatted for ReST E.g. for the line markerfacecolor property, which has an alias, return \'markerfacecolor or mfc\' and for the transform property, which does not, return \'transform\''
def aliased_name_rest(self, s, target):
if (s in self.aliasd): aliases = ''.join([(' or %s' % x) for x in self.aliasd[s].keys()]) else: aliases = '' return (':meth:`%s <%s>`%s' % (s, target, aliases))
'If *prop* is *None*, return a list of strings of all settable properies and their valid values. If *prop* is not *None*, it is a valid property name and that property will be returned as a string of property : valid values.'
def pprint_setters(self, prop=None, leadingspace=2):
if leadingspace: pad = (' ' * leadingspace) else: pad = '' if (prop is not None): accepts = self.get_valid_values(prop) return ('%s%s: %s' % (pad, prop, accepts)) attrs = self._get_setters_and_targets() attrs.sort() lines = [] for (prop, path) in attrs: ...
'If *prop* is *None*, return a list of strings of all settable properies and their valid values. Format the output for ReST If *prop* is not *None*, it is a valid property name and that property will be returned as a string of property : valid values.'
def pprint_setters_rest(self, prop=None, leadingspace=2):
if leadingspace: pad = (' ' * leadingspace) else: pad = '' if (prop is not None): accepts = self.get_valid_values(prop) return ('%s%s: %s' % (pad, prop, accepts)) attrs = self._get_setters_and_targets() attrs.sort() lines = [] names = [self.aliased_name_...
'Return the getters and actual values as list of strings.'
def pprint_getters(self):
o = self.oorig getters = [name for name in dir(o) if (name.startswith('get_') and callable(getattr(o, name)))] getters.sort() lines = [] for name in getters: func = getattr(o, name) if self.is_alias(func): continue try: val = func() except: ...
'Recursively find all :class:`matplotlib.artist.Artist` instances contained in *self*. If *match* is not None, it can be - function with signature ``boolean = match(artist)`` - class instance: eg :class:`~matplotlib.lines.Line2D` used to filter matches.'
def findobj(self, match=None):
if (match is None): def matchfunc(x): return True elif issubclass(match, Artist): def matchfunc(x): return isinstance(x, match) elif callable(match): matchfunc = func else: raise ValueError('match must be None, an matplotlib.artist.A...
'supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text'
def __getattr__(self, aname):
if (aname == 'lineno'): return lineno(self.loc, self.pstr) elif (aname in ('col', 'column')): return col(self.loc, self.pstr) elif (aname == 'line'): return line(self.loc, self.pstr) else: raise AttributeError(aname)
'Extracts the exception line from the input string, and marks the location of the exception with a special symbol.'
def markInputline(self, markerString='>!<'):
line_str = self.line line_column = (self.column - 1) if markerString: line_str = ''.join([line_str[:line_column], markerString, line_str[line_column:]]) return line_str.strip()
'Returns all named result keys.'
def keys(self):
return self.__tokdict.keys()
'Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.'
def pop(self, index=(-1)):
ret = self[index] del self[index] return ret
'Returns named result matching the given key, or if there is no such name, then returns the given defaultValue or None if no defaultValue is specified.'
def get(self, key, defaultValue=None):
if (key in self): return self[key] else: return defaultValue
'Returns all named result keys and values as a list of tuples.'
def items(self):
return [(k, self[k]) for k in self.__tokdict]
'Returns all named result values.'
def values(self):
return [v[(-1)][0] for v in self.__tokdict.values()]
'Returns the parse results as a nested list of matching tokens, all converted to strings.'
def asList(self):
out = [] for res in self.__toklist: if isinstance(res, ParseResults): out.append(res.asList()) else: out.append(res) return out
'Returns the named parse results as dictionary.'
def asDict(self):
return dict(self.items())
'Returns a new copy of a ParseResults object.'
def copy(self):
ret = ParseResults(self.__toklist) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name return ret
'Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.'
def asXML(self, doctag=None, namedItemsOnly=False, indent='', formatted=True):
nl = '\n' out = [] namedItems = dict([(v[1], k) for (k, vlist) in self.__tokdict.items() for v in vlist]) nextLevelIndent = (indent + ' ') if (not formatted): indent = '' nextLevelIndent = '' nl = '' selfTag = None if (doctag is not None): selfTag = doc...
'Returns the results name for this token expression.'
def getName(self):
if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif ((len(self) == 1) and (len(self.__tokdict) == 1) and (self.__tokdict.values()[0][0][1] in (0, (-1)))): return ...
'Diagnostic method for listing out the contents of a ParseResults. Accepts an optional indent argument so that this string can be embedded in a nested display of other data.'
def dump(self, indent='', depth=0):
out = [] out.append((indent + _ustr(self.asList()))) keys = self.items() keys.sort() for (k, v) in keys: if out: out.append('\n') out.append(('%s%s- %s: ' % (indent, (' ' * depth), k))) if isinstance(v, ParseResults): if v.keys(): ...
'Overrides the default whitespace chars'
def setDefaultWhitespaceChars(chars):
ParserElement.DEFAULT_WHITE_CHARS = chars
'Make a copy of this ParserElement. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.'
def copy(self):
cpy = copy.copy(self) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
'Define name for this expression, for use in debugging.'
def setName(self, name):
self.name = name self.errmsg = ('Expected ' + self.name) if hasattr(self, 'exception'): self.exception.msg = self.errmsg return self
'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.'
def setResultsName(self, name, listAllMatches=False):
newself = self.copy() newself.resultsName = name newself.modalResults = (not listAllMatches) return newself
'Method to invoke the Python pdb debugger when this element is about to be parsed. Set breakFlag to True to enable, False to disable.'
def setBreak(self, breakFlag=True):
if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() _parseMethod(instring, loc, doActions, callPreParse) breaker._originalParseMethod = _parseMethod self._parse = breake...
'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).'
def _normalizeParseActionArgs(f):
STAR_ARGS = 4 try: restore = None if isinstance(f, type): restore = f f = f.__init__ if (not _PY3K): codeObj = f.func_code else: codeObj = f.code if (codeObj.co_flags & STAR_ARGS): return f numargs = code...
'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 =...
def setParseAction(self, *fns, **kwargs):
self.parseAction = list(map(self._normalizeParseActionArgs, list(fns))) self.callDuringTry = (('callDuringTry' in kwargs) and kwargs['callDuringTry']) return self
'Add parse action to expression\'s list of parse actions. See L{I{setParseAction}<setParseAction>}.'
def addParseAction(self, *fns, **kwargs):
self.parseAction += list(map(self._normalizeParseActionArgs, list(fns))) self.callDuringTry = (self.callDuringTry or (('callDuringTry' in kwargs) and kwargs['callDuringTry'])) return self
'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 fun...
def setFailAction(self, fn):
self.failAction = fn return self
'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 exception...
def enablePackrat():
if (not ParserElement._packratEnabled): ParserElement._packratEnabled = True ParserElement._parse = ParserElement._parseCache
'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: pa...
def parseString(self, instring, parseAll=False):
ParserElement.resetCache() if (not self.streamlined): self.streamline() for e in self.ignoreExprs: e.streamline() if (not self.keepTabs): instring = instring.expandtabs() (loc, tokens) = self._parse(instring, 0) if parseAll: StringEnd()._parse(instring, loc) r...
'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...
def scanString(self, instring, maxMatches=_MAX_INT):
if (not self.streamlined): self.streamline() for e in self.ignoreExprs: e.streamline() if (not self.keepTabs): instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() ...
'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 matc...
def transformString(self, instring):
out = [] lastE = 0 self.keepTabs = True for (t, s, e) in self.scanString(instring): out.append(instring[lastE:s]) if t: if isinstance(t, ParseResults): out += t.asList() elif isinstance(t, list): out += t else: ...
'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.'
def searchString(self, instring, maxMatches=_MAX_INT):
return ParseResults([t for (t, s, e) in self.scanString(instring, maxMatches)])
'Implementation of + operator - returns And'
def __add__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return And([self, other])
'Implementation of + operator when left operand is not a ParserElement'
def __radd__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other + self)
'Implementation of - operator, returns And with error stop'
def __sub__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return And([self, And._ErrorStop(), ...
'Implementation of - operator when left operand is not a ParserElement'
def __rsub__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other - self)
'Implementation of | operator - returns MatchFirst'
def __or__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return MatchFirst([self, other])
'Implementation of | operator when left operand is not a ParserElement'
def __ror__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other | self)
'Implementation of ^ operator - returns Or'
def __xor__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return Or([self, other])
'Implementation of ^ operator when left operand is not a ParserElement'
def __rxor__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other ^ self)
'Implementation of & operator - returns Each'
def __and__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return Each([self, other])
'Implementation of & operator when left operand is not a ParserElement'
def __rand__(self, other):
if isinstance(other, basestring): other = Literal(other) if (not isinstance(other, ParserElement)): warnings.warn(('Cannot combine element of type %s with ParserElement' % type(other)), SyntaxWarning, stacklevel=2) return None return (other & self)
'Implementation of ~ operator - returns NotAny'
def __invert__(self):
return NotAny(self)
'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")'
def __call__(self, name):
return self.setResultsName(name)