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 with the contains test. ACCEPTS: a callable function'
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_children(): a.pick(mouseevent)
'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 interpreted as an epsilon tolerance in points and the artist will fire off an event if it\'s data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g. the indices of the data within epsilon of the pick event * A function: if picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) to determine the hit test. if the mouse event is over the artist, return *hit=True* and props is a dictionary of properties you want added to the PickEvent attributes. ACCEPTS: [None|float|boolean|callable]'
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*, to remove the clipping path For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to *None*. ACCEPTS: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]'
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): self._clippath = TransformedPath(path.get_path(), path.get_transform()) success = True if (path is None): self._clippath = None success = True elif isinstance(path, Path): self._clippath = TransformedPath(path, transform) success = True if (not success): print type(path), type(transform) raise TypeError('Invalid arguments to set_clip_path') self.pchanged()
'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 self.eventson = store if changed: self.pchanged()
'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.pchanged()
'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. Only return artists of class type .. plot:: mpl_examples/pylab_examples/findobj_demo.py'
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 matplotlib.artist.Artist subclass, or a callable') artists = [] for c in self.get_children(): if matchfunc(c): artists.append(c) artists.extend([thisc for thisc in c.findobj(matchfunc) if matchfunc(thisc)]) if matchfunc(self): artists.append(self) return artists
'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__ fullname = docstring[10:] aliases.setdefault(fullname[4:], {})[name[4:]] = None return aliases
'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 '): return None match = self._get_valid_values_regex.search(docstring) if (match is not None): return match.group(1).replace('\n', ' ') return 'unknown'
'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.o.__name__) for cls in self.o.mro(): if (name in cls.__dict__): source_class = ((cls.__module__ + '.') + cls.__name__) break setters.append((name[4:], ((source_class + '.') + name))) return setters
'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: accepts = self.get_valid_values(prop) name = self.aliased_name(prop) lines.append(('%s%s: %s' % (pad, name, accepts))) return lines
'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_rest(prop, target) for (prop, target) in attrs] accepts = [self.get_valid_values(prop) for (prop, target) in attrs] col0_len = max([len(n) for n in names]) col1_len = max([len(a) for a in accepts]) table_formatstr = (((pad + ('=' * col0_len)) + ' ') + ('=' * col1_len)) lines.append('') lines.append(table_formatstr) lines.append(((pad + 'Property'.ljust((col0_len + 3))) + 'Description'.ljust(col1_len))) lines.append(table_formatstr) lines.extend([((pad + n.ljust((col0_len + 3))) + a.ljust(col1_len)) for (n, a) in zip(names, accepts)]) lines.append(table_formatstr) lines.append('') return lines for (prop, path) in attrs: accepts = self.get_valid_values(prop) name = self.aliased_name_rest(prop, path) lines.append(('%s%s: %s' % (pad, name, accepts))) return lines
'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: continue if ((getattr(val, 'shape', ()) != ()) and (len(val) > 6)): s = (str(val[:6]) + '...') else: s = str(val) s = s.replace('\n', ' ') if (len(s) > 50): s = (s[:50] + '...') name = self.aliased_name(name[4:]) lines.append((' %s = %s' % (name, s))) return lines
'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.Artist subclass, or a callable') artists = [] for c in self.get_children(): if matchfunc(c): artists.append(c) artists.extend([thisc for thisc in c.findobj(matchfunc) if matchfunc(thisc)]) if matchfunc(self): artists.append(self) return artists
'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 = doctag elif self.__name: selfTag = self.__name if (not selfTag): if namedItemsOnly: return '' else: selfTag = 'ITEM' out += [nl, indent, '<', selfTag, '>'] worklist = self.__toklist for (i, res) in enumerate(worklist): if isinstance(res, ParseResults): if (i in namedItems): out += [res.asXML(namedItems[i], (namedItemsOnly and (doctag is None)), nextLevelIndent, formatted)] else: out += [res.asXML(None, (namedItemsOnly and (doctag is None)), nextLevelIndent, formatted)] else: resTag = None if (i in namedItems): resTag = namedItems[i] if (not resTag): if namedItemsOnly: continue else: resTag = 'ITEM' xmlBodyText = xml.sax.saxutils.escape(_ustr(res)) out += [nl, nextLevelIndent, '<', resTag, '>', xmlBodyText, '</', resTag, '>'] out += [nl, indent, '</', selfTag, '>'] return ''.join(out)
'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 self.__tokdict.keys()[0] else: return None
'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(): out.append(v.dump(indent, (depth + 1))) else: out.append(_ustr(v)) else: out.append(_ustr(v)) return ''.join(out)
'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 = breaker elif hasattr(self._parse, '_originalParseMethod'): self._parse = self._parse._originalParseMethod return self
'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 = codeObj.co_argcount if (not _PY3K): if hasattr(f, 'im_self'): numargs -= 1 elif hasattr(f, '__self__'): numargs -= 1 if restore: f = restore except AttributeError: try: if (not _PY3K): call_im_func_code = f.__call__.im_func.func_code else: call_im_func_code = f.__code__ if (call_im_func_code.co_flags & STAR_ARGS): return f numargs = call_im_func_code.co_argcount if (not _PY3K): if hasattr(f.__call__, 'im_self'): numargs -= 1 elif hasattr(f.__call__, '__self__'): numargs -= 0 except AttributeError: if (not _PY3K): call_func_code = f.__call__.func_code else: call_func_code = f.__call__.__code__ if (call_func_code.co_flags & STAR_ARGS): return f numargs = call_func_code.co_argcount if (not _PY3K): if hasattr(f.__call__, 'im_self'): numargs -= 1 elif hasattr(f.__call__, '__self__'): numargs -= 1 if (numargs == 3): return f else: if (numargs > 3): def tmp(s, l, t): return f(f.__call__.__self__, s, l, t) if (numargs == 2): def tmp(s, l, t): return f(l, t) elif (numargs == 1): def tmp(s, l, t): return f(t) else: def tmp(s, l, t): return f() try: tmp.__name__ = f.__name__ except (AttributeError, TypeError): pass try: tmp.__doc__ = f.__doc__ except (AttributeError, TypeError): pass try: tmp.__dict__.update(f.__dict__) except (AttributeError, TypeError): pass return tmp
'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.'
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 function returns no value. It may throw ParseFatalException if it is desired to stop parsing immediately.'
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 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.'
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: 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'
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) return tokens
'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.'
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() matches = 0 while ((loc <= instrlen) and (matches < maxMatches)): try: preloc = preparseFn(instring, loc) (nextLoc, tokens) = parseFn(instring, preloc, callPreParse=False) except ParseException: loc = (preloc + 1) else: matches += 1 (yield (tokens, preloc, nextLoc)) loc = nextLoc
'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.'
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: out.append(t) lastE = e out.append(instring[lastE:]) return ''.join(map(_ustr, out))
'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(), other])
'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)