boopak.sparse
index
boopak/sparse.py

sparse: A module which implements simple S-expressions.
 
An S-expression is a string, or a parenthesized list of S-expressions.
In other words, good old Lisp-style expressions. This implementation
also allows named elements in lists (as well as the usual positional
elements).
 
The following are valid S-expressions:
 
  string
  ()
  (string)
  (one two three)
  (key=value key2=value2)
  (list (containing a list) and ((another)))
  (one two named=(inner (list) ()))
 
A string can containing special characters -- whitespace, quotes, equals,
parentheses -- if it is quoted. Single or double quotes can be used.
Inside a quoted string, quotes and backslashes should be escaped with
a backslash. So the following are also valid:
 
  "quote " mark"
  'single quote ' mark'
  "smiley =o) clown"
 
Note that these three expressions are identical:
 
  string
  "string"
  'string'
 
However, the following are not identical:
 
  (string)
  "(string)"
 
The former is a list containing one string; the latter is a string.
 
This module lets you convert the textual representation of an expression
into a structured representation -- a tree of Tree objects. (The subclasses
of Tree are List and ID, representing lists and strings.)
 
Classes:
 
Tree -- represents an S-expression
List -- subclass which represents a list expression
ID -- subclass which represents a string expression
 
Public functions:
 
parse() -- parse a string which contains exactly one S-expression
 
Internal classes:
 
AttrToken -- represents a named value encountered during parsing
ParseContext -- represents the state of an ongoing parse() operation

 
Modules
       
codecs
io

 
Classes
       
builtins.Exception(builtins.BaseException)
ParseError
builtins.object
AttrToken
ParseContext
Tree
ID
List

 
class AttrToken(builtins.object)
    AttrToken(key)
 
AttrToken: represents a named value encountered during parsing.
 
This is an internal class; it should not be used outside this module.
 
  Methods defined here:
__init__(self, key)
Initialize self.  See help(type(self)) for accurate signature.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class ID(Tree)
    ID(id)
 
ID: represents a string expression.
 
    ID(val) -- constructor
 
The value that you pass to the constructor is a str.  It becomes the ID's
underlying string value, so it should not be quoted or escaped.
 
For any str val,
 
    ID(val).as_string() == val
 
 
Method resolution order:
ID
Tree
builtins.object

Methods defined here:
__eq__(self, other)
Return self==value.
__ge__(self, other, NotImplemented=NotImplemented)
Return a >= b.  Computed by @total_ordering from (not a < b).
__gt__(self, other, NotImplemented=NotImplemented)
Return a > b.  Computed by @total_ordering from (not a < b) and (a != b).
__init__(self, id)
Initialize self.  See help(type(self)) for accurate signature.
__le__(self, other, NotImplemented=NotImplemented)
Return a <= b.  Computed by @total_ordering from (a < b) or (a == b).
__len__(self)
__lt__(self, other)
Return self<value.
as_boolean(self)
as_boolean() -> bool
 
Get the boolean value which this tree represents. The empty
string is considered false, as are '0', 'no', or 'false'. Or
really any string beginning with '0', 'n', 'N', 'f', or 'F'.
Anything else is true.
 
Raises ValueError if called on a List.
as_float(self)
as_float() -> float
 
Get the float value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as a float.
as_integer(self)
as_integer() -> int or long
 
Get the integer value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as an integer.
as_string(self)
as_string() -> str
 
Get the string which this tree represents. (The result is not
quoted or escaped; it is the underlying string value.)
 
Raises ValueError if called on a List.
serialize(self)
serialize() -> str
 
Convert this tree into its textual representation. Strings will
be quoted and escaped if necessary.

Data and other attributes defined here:
__hash__ = None

Methods inherited from Tree:
__repr__(self)
Return repr(self).

Data descriptors inherited from Tree:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class List(Tree)
    List(*args, **attrs)
 
List: represents a list expression.
 
A list can contain positional entries and named values; it therefore
acts as both an array and a dict.
 
Array-style operations:
 
    len(l)
    l[int]
    l[int:int]
    l.append(tree)
 
Dict-style operations:
 
    l.has_attr(key)
    l.get_attr(key)
    l.set_attr(key, tree)
 
(The keys in these operations must be strings.)
 
Positional (array) values and named (dict) values are separate. If l
has no positional values, len(l) is zero, no matter how many named
values it has. Contrariwise, l.get_attr() will never retrieve a
positional value.
 
    List(val, val, ... key=val, key=val) -- constructor
 
Construct a List with the given named and/or positional values. All
values must be Trees. You can also construct a List from a Python
list or dict, using the forms List(*list) or List(**dict).
 
 
Method resolution order:
List
Tree
builtins.object

Methods defined here:
__contains__(self, it)
__getitem__(self, key)
__init__(self, *args, **attrs)
Initialize self.  See help(type(self)) for accurate signature.
__iter__(self)
__len__(self)
append(self, val)
append(val) -> None
 
Add the Tree as the last positional entry.
get_attr(self, key)
get_attr(key) -> Tree
 
Retrieve the named Tree which has the given key. If there is
no entry with that key, returns None.
has_attr(self, key)
has_attr(key) -> bool
 
Returns whether there is an entry with the given key.
serialize(self)
serialize() -> str
 
Convert this tree into its textual representation. Strings will
be quoted and escaped if necessary.
set_attr(self, key, val)
set_attr(key, val) -> None
 
Add the Tree val as a named entry, with the given key.

Methods inherited from Tree:
__repr__(self)
Return repr(self).
as_boolean(self)
as_boolean() -> bool
 
Get the boolean value which this tree represents. The empty
string is considered false, as are '0', 'no', or 'false'. Or
really any string beginning with '0', 'n', 'N', 'f', or 'F'.
Anything else is true.
 
Raises ValueError if called on a List.
as_float(self)
as_float() -> float
 
Get the float value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as a float.
as_integer(self)
as_integer() -> int or long
 
Get the integer value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as an integer.
as_string(self)
as_string() -> str
 
Get the string which this tree represents. (The result is not
quoted or escaped; it is the underlying string value.)
 
Raises ValueError if called on a List.

Data descriptors inherited from Tree:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class ParseContext(builtins.object)
    ParseContext(fl)
 
ParseContext: represents the state of an ongoing parse() operation.
 
Parsing S-expressions is quite simple; we only need a stream of
characters and the ability to look ahead by one. (Or, if you like,
the ability to push one character back onto the stream.)
 
Fields:
 
    fl -- a file-like object, from which characters are read.
    nextch -- if a character has been pushed back, it is here;
        if not, this is None.
 
Constructor:
 
    ParseContext(fl) -- constructor
 
  Methods defined here:
__init__(self, fl)
Initialize self.  See help(type(self)) for accurate signature.
close(self)
close() -> None
 
Shut down the parser, and close the underlying stream.
finalwhite(self)
finalwhite() -> None
 
Ensure that there are no more expressions in the stream. Trailing
whitespace is ignored.
 
Raises ParseError on failure.
parseattr(self)
parseattr() -> Tree
 
Parse the value part of a named value. The stream must be after
the equals sign.
parseid(self)
parseid() -> ID or AttrToken
 
Parse an unquoted string expression. The stream must be at the
beginning of the expression.
parselist(self)
parselist() -> List
 
Parse a parenthesized list expression. The stream must be at
the beginning of the list contents, after the open parenthesis.
parsestring(self)
parsestring() -> ID
 
Parse an quoted string expression. The stream must be at the
beginning of the expression, before the initial quote.
parsetree(self)
parsetree() -> Tree or EndOfList or AttrToken
 
Parse one expression from the stream, and return the Tree that
represents it. Leading whitespace is ignored.
 
EndOfList indicates that a closing parenthesis has been
reached; an AttrToken instance indicates a named value such
as x=y. These are not valid expressions on their own; they can
only occur inside lists.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class ParseError(builtins.Exception)
    ParseError: represents an error parsing string data into Trees.
 
 
Method resolution order:
ParseError
builtins.Exception
builtins.BaseException
builtins.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from builtins.Exception:
__init__(self, /, *args, **kwargs)
Initialize self.  See help(type(self)) for accurate signature.

Static methods inherited from builtins.Exception:
__new__(*args, **kwargs) from builtins.type
Create and return a new object.  See help(type) for accurate signature.

Methods inherited from builtins.BaseException:
__delattr__(self, name, /)
Implement delattr(self, name).
__getattribute__(self, name, /)
Return getattr(self, name).
__reduce__(...)
Helper for pickle.
__repr__(self, /)
Return repr(self).
__setattr__(self, name, value, /)
Implement setattr(self, name, value).
__setstate__(...)
__str__(self, /)
Return str(self).
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.

Data descriptors inherited from builtins.BaseException:
__cause__
exception cause
__context__
exception context
__dict__
__suppress_context__
__traceback__
args

 
class Tree(builtins.object)
    Tree: represents an S-expression.
 
This is a virtual base class. Do not instantiate it; instead use
the List or ID class.
 
  Methods defined here:
__repr__(self)
Return repr(self).
as_boolean(self)
as_boolean() -> bool
 
Get the boolean value which this tree represents. The empty
string is considered false, as are '0', 'no', or 'false'. Or
really any string beginning with '0', 'n', 'N', 'f', or 'F'.
Anything else is true.
 
Raises ValueError if called on a List.
as_float(self)
as_float() -> float
 
Get the float value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as a float.
as_integer(self)
as_integer() -> int or long
 
Get the integer value which this tree represents.
 
Raises ValueError if called on a List, or on a string which
is not interpretable as an integer.
as_string(self)
as_string() -> str
 
Get the string which this tree represents. (The result is not
quoted or escaped; it is the underlying string value.)
 
Raises ValueError if called on a List.
serialize(self)
serialize() -> str
 
Convert this tree into its textual representation. Strings will
be quoted and escaped if necessary.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
parse(val)
parse(val) -> Tree
 
Parse a str or unicode value which contains *exactly one* S-expression.
The value must contain one string (possibly quoted), or one parenthesized
list. If the expression is ill-formed (unbalanced parentheses or quotes),
this raises ParseError.
 
Whitespace before or after the expression is ignored. Inside a list,
whitespace separates expressions, but the amount is not significant.
 
Note that parse('') raises ParseError, because it does not contain any
expression.

 
Data
        EndOfList = <object object>