boolean-py
The boolean.py library implements a boolean algebra, allowing users to define, create, and parse boolean expressions with variables and core boolean functions (AND, OR, NOT). It supports parsing expressions from strings, simplifying them, and comparing for equivalence. Additionally, it provides capabilities for creating custom boolean DSLs by extending its tokenizer and parser. The library is currently active, with its latest version being 5.0, and generally releases updates as needed for compatibility and features.
Warnings
- gotcha Boolean expressions created with `boolean-py` are not automatically evaluated or simplified upon construction. Users must explicitly call the `.simplify()` method on an expression to apply Boolean algebra laws and obtain its simplified form.
- gotcha The library natively provides `AND`, `OR`, and `NOT` as core operators. More complex boolean functions like `XOR` and `NAND` are not implemented directly and must be constructed by users through combinations of the basic operators.
- gotcha While `boolean-py` overloads the `~` operator for its `Symbol` instances (e.g., `~algebra.Symbol('x')` results in `NOT(Symbol('x'))`), users should be careful not to confuse this with Python's built-in `~` operator's behavior on standard `bool` values. In Python, `~True` evaluates to -2 and `~False` to -1, as `bool` is a subclass of `int`. This can be a source of confusion when transitioning between `boolean-py` expressions and standard Python boolean logic.
Install
-
pip install boolean-py
Imports
- BooleanAlgebra
from boolean.boolean import BooleanAlgebra
- boolean
import boolean
Quickstart
import boolean
algebra = boolean.BooleanAlgebra()
# Define symbols
fever = algebra.Symbol('fever')
cough = algebra.Symbol('cough')
headache = algebra.Symbol('headache')
# Create expressions
expression_string = "(fever | cough) & ~headache"
parsed_expression = algebra.parse(expression_string)
print(f"Parsed expression: {parsed_expression}")
# Evaluate the expression for specific symptoms
patient_symptoms = {
'fever': True,
'cough': False,
'headache': False
}
evaluated_expression = parsed_expression.subs(patient_symptoms)
simplified_result = evaluated_expression.simplify()
print(f"Evaluated result for symptoms: {simplified_result}")
# Direct Python expression construction
x, y, z = algebra.symbols('x', 'y', 'z')
expr2 = (x & y) | (~z)
print(f"Python-constructed expression: {expr2}")
print(f"Simplified expr2: {expr2.simplify()}")