boolean_parser Reference¶
General¶
- boolean_parser.parse(value, base='sqla')[source]¶
Convenience function to returned a parsed expression
Returns a parsed string using one of the available Parsers in
boolean_parser. Thebasekeyword argument can be used to select whichParserto use. The availble bases are: “base”, “sqla”. The default base is “sqla” which uses theboolean_parser.parsers.sqla.SQLAParser.- Parameters
value – str The string expression to evaluate and parse
base – str: The base Parser to use. Default is sqlalchemy parser.
- Returns
A parsed string using a Parsers object.
Actions¶
Boolean Actions¶
- class boolean_parser.actions.boolean.BaseBool(data)[source]¶
Bases:
objectBase class for handling conditions joined by boolean logic operators
This class handles the parsing of boolean logic within strings. The boolean classes are assigned to the
pyparsing.infixNotation()in the order of boolean NOTS->ANDS->ORS, i.e.BoolNot->BoolAnd->BoolOr. For example, the string “x > 1 and y < 2”, consisting of two conditions joined by a boolean “and” gets parsed into “and_(x>1, y<2)”, represented as “BoolAnd(Condition1, Condition2)”. During parsing, the class extracts all conditions and parameters joined by the boolean logic and makes them accessible as attributes.- Variables
params – list A list of extracted parameters from all conditions
conditions – list A list of conditions contained within the boolean clause
logicop – str The boolean logic operator used to join the conditions
- logicop = None¶
- property params¶
The extracted parameters from a parsed condition
- class boolean_parser.actions.boolean.BoolAnd(data)[source]¶
Bases:
boolean_parser.actions.boolean.BaseBoolClass for boolean And logic
- logicop = 'and'¶
- class boolean_parser.actions.boolean.BoolNot(data)[source]¶
Bases:
boolean_parser.actions.boolean.BaseBoolClass for boolean Not logic
- logicop = 'not'¶
- class boolean_parser.actions.boolean.BoolOr(data)[source]¶
Bases:
boolean_parser.actions.boolean.BaseBoolClass for boolean Or logic
- logicop = 'or'¶
Clause Actions¶
- class boolean_parser.actions.clause.BaseAction(data)[source]¶
Bases:
objectBase object representing a clause action
An action to perform after parsing a string clause. If set, actions run Actions are attached to clauses with the
setParseActionon a givenpyparsingelement.pyparsing.ParserElement.setParseAction()accepts a function or class to be applied to thepyparsingelement during the parsing process. Multiple actions can be attached by passing a list of functions or classes. This class extracts the parsed data from thepyparsingelement and makes it accessible as a variety of named attributes.- Variables
name – str The name of the extracted parameter
base – str The base name of the extracted parameter, if any.
fullname – str The full name of the extracted parameter as base + name
data – dict The extracted parsed parameters from the pyparse clause
parsed_clause –
pyparsing.ParseResultsThe original pyparsed results objectinput_clause – str The original input clause element
- property fullname¶
The full parameter name, including any base
- class boolean_parser.actions.clause.Condition(data)[source]¶
Bases:
boolean_parser.actions.clause.BaseActionClass action for handling conditional clauses
This action performs a basic conditional parse. The syntax for a conditional expressions is defined as “parameter operand value” or for “between” conditions, “parameter between value and value2”. The parameter name, operand, and parameter value is assigned as the
name,operator, andvalueattribute, respectively. Example conditional clauses: “x > 5” or “x > 5 and y < 3”. When using a “between” condition, e.g. “x between 3 and 5”, an additionalvalue2attribute is assigned the second parameter value. For bitwise operands of ‘&’ and ‘|’, the value can also accept a negation prefix, e.g. “x & ~256”, which evaluates to “x & -257”.- Allowed operands for conditionals are:
‘>’, ‘>=, ‘<’, ‘<=’, ‘==’, ‘=’, ‘!=’, ‘&’, ‘|’
In addition to the Base Attributes, the
Conditionaction provides additional attributes containing the parsed condition parameters.- Variables
operator – str The operand used in the condition
value – str The parameter value in the condition
value2 – str Optional second value, assigned when a “between” condition is used.
- property input_clause¶
Original input clause as a string
- class boolean_parser.actions.clause.Word(data)[source]¶
Bases:
boolean_parser.actions.clause.BaseActionClass action for handling word clauses
This action performs a basic word parse. The basic word is assigned as the
nameattribute. Example word clauses: “alpha” or “alpha and beta or not charlie”.- property input_clause¶
Original input clause as a string
Mixins¶
- class boolean_parser.mixins.sqla.SQLAMixin[source]¶
Bases:
objectA Mixin class to apply SQLAlchemy filter parsing
This mixin adds a
filtermethod to the parsed result which converts the parsed string object into an appropriate SQLAlchemy filter condition to be used in SQLAlchemy queries.- filter(modelclass)[source]¶
Return the condition as an SQLalchemy query filter condition
Loops over all models and creates a filter condition for that model given the input filter parameters.
- Parameters
modelclass (objects) – A set of ModelClasses to use in the filter condition
- Returns
A SQL query filter condition
Parsers¶
- class boolean_parser.parsers.base.Parser(value=None)[source]¶
Bases:
objectCore Parser class for parsing strings into objects
A core Parser class that can parse strings into a set of objects based on a defined set of string clause elements, and actions to perform for each clause.
- classmethod build_clause(clauses=None)[source]¶
Build a single clause from a list of clauses using pp.MatchFirst
Merges a list of clauses into a single clause using
pyparsing.MatchFirst. This is equivalent to “clause = clause1 | clause2 | clause3`. The clause precedence the Parser uses will be the order they appear in the list. The default is to use the attached Parser._clauses list.- Parameters
clauses – list A list of clauses to merge into a single clause
- classmethod build_parser(clauses=None, actions=None, bools=None)[source]¶
Builds a new boolean parser
Constructs a new boolean Parser class given a set of clauses, actions, and boolean objects. Clauses are individual
pyparsingelements that represent string clauses to pattern match on. Actions are functions or classes set on each clause element that control how that clause is parsed. See Clause Elements for the availablepyparsingclause elements.Assigns the default boolean classes,
[BoolNot, BoolAnd, BoolOr]to thepyparsing.infixNotation()such that NOTs->ANDs->ORs. Ifboolsis specified instead, uses those object classes to handle boolean logic.boolsmust be a list of length 3 containing classes for boolean “not”, “and”, and “or” logic in that order.- Parameters
clauses – list A list of pyparsing clause elements
actions – list A list of actions to attach to each clause element
bools – list A list of Boolean classes to use to handle boolean logic
Example
>>> from boolean_parser.parsers import Parser >>> from boolean_parser.clauses import condition, words >>> from boolean_parser.actions.clause import Condition, Word >>> >>> # Assign the parsing order precedence for clauses >>> clauses = [condition, words] >>> >>> # Create a list of Actions for each clause in clauses >>> actions = [Condition, Word] >>> >>> # build the Parser with these clauses and actions >>> Parser.build_parser(clauses=clauses, actions=actions)
- parse(value=None)[source]¶
Parse a string conditional
Calls
parseStringon thepyparsingclause element to parse the input string into apyparsing.ParseResultsobject.- Parameters
value – str The string expression to parse
- Returns
A pyparsing.ParseResults object
Example
>>> from boolean_parser.parsers import Parser >>> pp = Parser() >>> pp.parse('x > 1') >>> x>1
- classmethod set_clauses(clauses)[source]¶
Sets the list of clauses to use
- Parameters
clauses – list A list of clauses to attach to the Parser
- classmethod set_parse_actions(mapping=None, clauses=None, actions=None)[source]¶
Attach actions to a pyparsing clause element
pyparsingclause elements can have optional actions set with thesetParseActionwhich control how each clause is parsed. This maps a list of actions onto a list of clauses. Ifmappingis used, it must be a list of tuples containing which action to map to which clause. Otherwiseclausesandactionsmust be provided as equal-length lists which contain, for each item, what action(s) to attach to the corresponding clause.- Parameters
mapping – list of tuples A list of tuples containing a (clause, action) mapping.
clauses – list A list of clauses
actions – list A list of actions to attach to each clause
Example
>>> from boolean_parser.parsers import Parser >>> from boolean_parser.clauses import condition, words >>> from boolean_parser.actions.clause import Condition, Word >>> clauses = [condition, words] >>> actions = [Condition, Word] >>> Parser.set_parse_actions(clauses=clauses, actions=actions)
- property conditions¶
The extracted conditions from the parsed string
- property params¶
The extracted parameters from the parsed string
- class boolean_parser.parsers.sqla.SQLAAnd(data)[source]¶
Bases:
boolean_parser.actions.boolean.BoolAnd,boolean_parser.parsers.sqla.SQLBoolBaseSQLalchemy class for boolean And
- class boolean_parser.parsers.sqla.SQLACondition(data)[source]¶
Bases:
boolean_parser.mixins.sqla.SQLAMixin,boolean_parser.actions.clause.ConditionSQLAlchemy Conditional Action
Subclasses from
ConditionandSQLAMixinto create an action that parses a string that represents a SQLAlchemy filter condition and allows for conversion from the parsed string result to a SQLAlchemy filter object. For SQLAlchemy conditions, the syntax for a conditon expression is “database_table_name.parameter operand value” where “database_table_name.parameter” is a dotted syntax forModelClass.parameterwhich maps todbtable_name.column_name. For example, given a base ModelClass “TableModel” with parameter “x”, that maps to a database table called “table” with column “x”, the conditional expression “table.x < 4” parses into “{name: ‘x’, fullname: ‘table.x’, base: ‘table’, operator: ‘<’, value: ‘4’}”
- class boolean_parser.parsers.sqla.SQLANot(data)[source]¶
Bases:
boolean_parser.actions.boolean.BoolNot,boolean_parser.parsers.sqla.SQLBoolBaseSQLalchemy class for boolean Not
- class boolean_parser.parsers.sqla.SQLAOr(data)[source]¶
Bases:
boolean_parser.actions.boolean.BoolOr,boolean_parser.parsers.sqla.SQLBoolBaseSQLalchemy class for boolean Or
- class boolean_parser.parsers.sqla.SQLAParser(value=None)[source]¶
Bases:
boolean_parser.parsers.base.ParserA SQLAlchemy boolean parser object
A Parser class that provides a mechanism for converting a string conditional into a SQLAlchemy filter condition that can be passed into SQLAlchemy queries. This parser contains a
filtermethod which accepts a list of SQLAlchemy Model classes used to identify and convert the parsed parameter name into a SQLAlchemy Instrumented Attribute.Example
>>> from boolean_parser.parsers import SQLAParser >>> from database.models import TableModel >>> from database import session >>> >>> # create the parser and parse a sql condition >>> res = SQLParser('table.x > 5 and table.y < 2').parse() >>> res >>> and_(x>5, y<2) >>> >>> # generate the sqlalchemy filter >>> ff = res.filter(TableModel) >>> print(ff.compile(compile_kwargs={'literal_binds': True})) >>> table.x > 5 AND table.y < 2 >>> >>> # perform the sqlalchemy query >>> session.query(TableModel).filter(ff).all()
- class boolean_parser.parsers.sqla.SQLBoolBase(data)[source]¶
Bases:
boolean_parser.actions.boolean.BaseBoolClass for handling boolean logic joins for SQLALchemy filter expressions
