### Basic Boolean Algebra Setup Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Demonstrates the basic setup for using the BooleanAlgebra library, including creating symbols and building expressions using operators and the parse method. ```python from boolean import BooleanAlgebra algebra = BooleanAlgebra() # Create symbols a, b, c = algebra.symbols('a', 'b', 'c') # Build expressions with operators expr = a & (b | c) expr2 = algebra.NOT(a) expr3 = algebra.parse('(a or b) and not c') ``` -------------------------------- ### Install boolean.py Source: https://github.com/bastikr/boolean.py/blob/master/docs/users_guide.md Install the boolean.py library using pip. ```sh pip install boolean.py ``` -------------------------------- ### Custom Algebra Setup Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Illustrates how to create a custom BooleanAlgebra with alternative operators for AND and OR. ```APIDOC ### Custom algebra with alternative operators ```python class CustomAND(AND): def __init__(self, *args): super().__init__(*args) self.operator = 'AND' class CustomOR(OR): def __init__(self, *args): super().__init__(*args) self.operator = 'OR' custom_algebra = BooleanAlgebra(AND_class=CustomAND, OR_class=CustomOR) expr = custom_algebra.parse('a AND b OR c') ``` ``` -------------------------------- ### BooleanAlgebra Setup Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Demonstrates how to initialize and use the BooleanAlgebra class, including creating symbols and building expressions. ```APIDOC ## Usage Patterns ### Basic algebra setup ```python from boolean import BooleanAlgebra algebra = BooleanAlgebra() # Create symbols a, b, c = algebra.symbols('a', 'b', 'c') # Build expressions with operators expr = a & (b | c) expr2 = algebra.NOT(a) expr3 = algebra.parse('(a or b) and not c') ``` ``` -------------------------------- ### Run Doc Tests Source: https://github.com/bastikr/boolean.py/wiki/Development Install Sphinx and run documentation tests. Navigate to the 'doc' directory before executing these commands. ```bash cd doc make doctest ``` -------------------------------- ### AND Constructor and Usage Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Demonstrates creating AND expressions using the '&' operator, '*' operator, and direct instantiation. Includes examples with TRUE/FALSE for identity and annihilation. ```python a, b, c = algebra.symbols('a', 'b', 'c') # Using & operator expr1 = a & b expr2 = a & b & c # Using * operator expr3 = a * b # Direct instantiation expr4 = algebra.AND(a, b, c) expr5 = algebra.AND(a, algebra.OR(b, c)) # With TRUE/FALSE expr6 = a & algebra.TRUE # Simplifies to a (identity) expr7 = a & algebra.FALSE # Simplifies to FALSE (annihilation) ``` -------------------------------- ### AND Simplification Example Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Shows how to simplify an AND expression to its canonical form. Demonstrates simplification of repeated terms and annihilation with FALSE. ```python expr = algebra.parse('a and a and a', simplify=False) simplified = expr.simplify() # Returns single Symbol('a') expr2 = algebra.AND(a, algebra.FALSE) expr2.simplify() # Returns FALSE ``` -------------------------------- ### Tokenizer Output Example Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Demonstrates the structure of tokens produced by the tokenizer, which is an iterable of 3-tuples: (token_type, token_string, token_position). ```python tokens = list(algebra.tokenize('a and (b or c)')) # [ # (TOKEN_SYMBOL, 'a', 0), # (TOKEN_AND, 'and', 2), # (TOKEN_LPAR, '(', 6), # (TOKEN_SYMBOL, 'b', 7), # (TOKEN_OR, 'or', 9), # (TOKEN_SYMBOL, 'c', 12), # (TOKEN_RPAR, ')', 13), # ] ``` -------------------------------- ### ParseError Constructor Example Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/errors.md Demonstrates how to manually create a ParseError instance. This is rarely needed as the library raises this exception automatically upon encountering errors. ```python from boolean import ParseError, PARSE_INVALID_EXPRESSION # Create a ParseError manually (rarely needed) error = ParseError( error_code=PARSE_INVALID_EXPRESSION, token_string="", position=5 ) ``` -------------------------------- ### Create Symbols and Get Definitions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Generate symbols for use in expressions and retrieve the library's default definitions for TRUE, FALSE, and operators. ```python # Create symbols a, b, c = algebra.symbols('a', 'b', 'c') # Get definition true, false, not_op, and_op, or_op, sym_class = algebra.definition() ``` -------------------------------- ### Expression Parsing Examples Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Illustrates the different types of expressions returned by the algebra.parse() method, including boolean singletons, symbols, and logical operations. ```python expr1 = algebra.parse('True') # Returns _TRUE expr2 = algebra.parse('a') # Returns Symbol expr3 = algebra.parse('not a') # Returns NOT expr4 = algebra.parse('a and b') # Returns AND expr5 = algebra.parse('a or b') # Returns OR ``` -------------------------------- ### ParseError.__str__() Method Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/errors.md Explains how to get a human-readable string representation of the ParseError. ```APIDOC ## ParseError.__str__() Method ### Description Return a formatted error message. ### Returns `str` — Human-readable error message. ### Example ```python try: algebra.parse('a @ b') except ParseError as e: print(str(e)) # Output: "Unknown token for token: "@" at position: 2" ``` The formatted message includes: - The error description from PARSE_ERRORS - The problematic token (if token_string is set) - The position in the input (if position > 0) ``` -------------------------------- ### Retrieve Algebra Definition Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Call `definition` to get the configured TRUE, FALSE, NOT, AND, OR, and Symbol classes/singletons for the current algebra instance. ```python true, false, not_op, and_op, or_op, sym = algebra.definition() ``` -------------------------------- ### Create Symbols with Different Identifiers Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Demonstrates creating Symbol objects using strings, numbers, and tuples as identifiers. Includes examples with special characters in string identifiers. ```python # String identifiers (most common) a = Symbol('a') # Numeric identifiers sym = Symbol(42) # Tuple identifiers (for composite names) sym = Symbol(('namespace', 'key')) # Special characters in string identifiers (with appropriate allowed_in_token) sym = Symbol('user@domain.com') sym = Symbol('config.value') sym = Symbol('api:endpoint') ``` -------------------------------- ### Apply Distributive Laws (OR over AND) Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Use distributive() to apply the distributive law where OR distributes over AND. For example, A | (B & C) becomes (A | B) & (A | C). ```python # A | (B & C) = (A | B) & (A | C) expr2 = algebra.OR(a, algebra.AND(b, c)) expr2.distributive() # Returns: AND(OR(a, b), OR(a, c)) ``` -------------------------------- ### Accessing TRUE Element Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Instantiate a BooleanAlgebra and access its TRUE element. This is the standard way to get the TRUE singleton. ```python algebra = BooleanAlgebra(); true_val = algebra.TRUE ``` -------------------------------- ### Regenerate HTML Documentation Source: https://github.com/bastikr/boolean.py/wiki/Development Generate HTML documentation after installing Sphinx and potentially extra Linux packages like texlive-full and dvipng. This process is recommended to be performed on a Linux environment from the 'doc' directory. ```bash make html ``` -------------------------------- ### Custom TRUE and FALSE Classes Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Example of creating custom classes for TRUE and FALSE elements to alter their string representation. Requires importing _TRUE and _FALSE. ```python class MyTRUE(_TRUE): def __str__(self): return "YES" def __repr__(self): return "YES" class MyFALSE(_FALSE): def __str__(self): return "NO" def __repr__(self): return "NO" from boolean import _TRUE, _FALSE algebra = BooleanAlgebra(TRUE_class=MyTRUE, FALSE_class=MyFALSE) print(algebra.TRUE) # Output: YES print(algebra.FALSE) # Output: NO ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/bastikr/boolean.py/blob/master/docs/development_guide.md Test boolean.py across multiple supported Python environments using tox. Ensure development requirements are installed first. ```shell pip install -r requirements-dev.txt tox ``` -------------------------------- ### Apply Distributive Laws (AND over OR) Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Use distributive() to apply the distributive law where AND distributes over OR. For example, A & (B | C) becomes (A & B) | (A & C). ```python # A & (B | C) = (A & B) | (A & C) expr = algebra.AND(a, algebra.OR(b, c)) expr.distributive() # Returns: OR(AND(a, b), AND(a, c)) ``` -------------------------------- ### Evaluate Truth Table for XOR Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Generates and prints a truth table for a given boolean expression, demonstrating how to evaluate it for all possible input combinations. This example specifically shows XOR logic. ```python a, b = algebra.symbols('a', 'b') expr = (a | b) & ~(a & b) # XOR logic print("A | B | Result") for av in [True, False]: for bv in [True, False]: result = expr(a=av, b=bv) print(f"{av} | {bv} | {result}") ``` -------------------------------- ### Basic ParseError Handling Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/errors.md A fundamental example of using a try-except block to catch `ParseError` during expression parsing. It shows how to access error details like the message, code, token, and position. ```python from boolean import BooleanAlgebra, ParseError algebra = BooleanAlgebra() try: expr = algebra.parse(user_input) except ParseError as e: print(f"Parse error: {e}") print(f"Error code: {e.error_code}") print(f"Token: {e.token_string}") print(f"Position: {e.position}") ``` -------------------------------- ### Parameters Accepting Expressions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Methods accepting `Expression` parameters can take any subtype of `Expression`. Examples show valid combinations of AND, OR, and NOT operations with symbols and constants. ```python # All valid algebra.AND(symbol, algebra.TRUE) algebra.AND(symbol, algebra.NOT(another_symbol)) algebra.AND(algebra.OR(x, y), algebra.AND(z, w)) algebra.NOT(algebra.AND(a, b, c)) ``` -------------------------------- ### Getting Full Error Context with ParseError Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/errors.md Shows how to use a try-except block to catch ParseError and extract detailed information like error code, message, token string, and position. It also includes printing the full traceback. ```Python import traceback try: expr = algebra.parse(user_expr) except ParseError as e: print(f"ParseError details:") print(f" Code: {e.error_code}") print(f" Message: {e}") print(f" Token: '{e.token_string}'") print(f" Position: {e.position}") traceback.print_exc() ``` -------------------------------- ### Implement Custom Tokenizer with Domain-Specific Syntax Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Override the tokenize method to define custom operators and constants. This example introduces 'PERHAPS' for OR, 'SURELY' for AND, 'FORGET' for NOT, and custom TRUE/FALSE values. ```python from boolean import BooleanAlgebra, TOKEN_SYMBOL, TOKEN_AND, TOKEN_OR, TOKEN_NOT, TOKEN_LPAR, TOKEN_RPAR class CustomAlgebra(BooleanAlgebra): """ Custom tokenizer supporting domain-specific syntax. """ def tokenize(self, expr): """ Tokenize with custom operators. """ operators = { 'PERHAPS': TOKEN_OR, # Custom OR 'SURELY': TOKEN_AND, # Custom AND 'FORGET': TOKEN_NOT, # Custom NOT } for pos, token in enumerate(expr.split()): token_lower = token.lower() if token_lower in operators: yield operators[token_lower], token, pos elif token == '(': yield TOKEN_LPAR, token, pos elif token == ')': yield TOKEN_RPAR, token, pos elif token_lower in ('true', 'yes'): # Custom TRUE constant yield self.Symbol('__TRUE__'), token, pos elif token_lower in ('false', 'no'): # Custom FALSE constant yield self.Symbol('__FALSE__'), token, pos else: # Regular symbol yield TOKEN_SYMBOL, token, pos # Usage algebra = CustomAlgebra() expr = algebra.parse('license_needed SURELY permission_granted PERHAPS admin_role FORGET guest_status') print(expr) ``` -------------------------------- ### Type Checking Boolean Expressions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Provides examples of using isinstance() to check the type of parsed boolean expressions and their components, verifying they match expected classes like Expression, AND, Symbol, _TRUE, and NOT. ```python from boolean import Expression, Symbol, BooleanAlgebra from boolean.boolean import _TRUE, _FALSE, NOT, AND, OR, Function expr = algebra.parse('a and b') isinstance(expr, Expression) # True (all expressions) isinstance(expr, AND) # True (specific operation) isinstance(expr.args[0], Symbol) # True isinstance(algebra.TRUE, _TRUE) # True (base element) isinstance(~algebra.Symbol('x'), NOT) # True ``` -------------------------------- ### Get Literals from an Expression Source: https://github.com/bastikr/boolean.py/blob/master/docs/users_guide.md Use the `literals` attribute to get a set of literals in an expression, or `get_literals()` to get a list. This helps in isolating and processing literal terms. ```python >>> import boolean >>> algebra = boolean.BooleanAlgebra() >>> x, y, z = algebra.symbols('x', 'y', 'z') >>> x.literals {Symbol('x')} >>> (~(x|~y)).get_literals() [Symbol('x'), NOT(Symbol('y'))] ``` -------------------------------- ### Get All Symbols Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Retrieves a list of all Symbol instances within an expression, including duplicates and those in subexpressions. ```python expr = algebra.parse('a and a and b') syms = expr.get_symbols() # Returns: [Symbol('a'), Symbol('a'), Symbol('b')] ``` -------------------------------- ### Get All Literals Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Retrieves a list of all literal expressions within an expression, including duplicates and those in subexpressions. ```python expr = algebra.parse('a and a and not b') lits = expr.get_literals() # Returns: [Symbol('a'), Symbol('a'), NOT(Symbol('b'))] ``` -------------------------------- ### Configuration and Customization Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/INDEX.txt Details constructor options, custom tokenization, and configuration presets. ```APIDOC ## Configuration and Customization ### Description This section covers the various options available for configuring the `BooleanAlgebra` instance and customizing its behavior, particularly regarding parsing and tokenization. ### Constructor Options - **Parameter specifications**: Detailed descriptions of all 6 constructor parameters. - **Examples**: Usage patterns and examples for different configuration settings. ### Custom Tokenization - **Custom tokenizer patterns**: How to define and use custom regular expressions or rules for tokenizing input strings. ### Configuration Presets - Information on any predefined configuration settings that can be easily applied. ### Advanced Usage - **Multi-algebra usage**: Patterns for working with multiple independent boolean algebra configurations. - **Best practices**: Recommendations for effective configuration and usage. - **Testing patterns**: Strategies for testing custom configurations. ``` -------------------------------- ### TRUE Element Detailed Representation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Get the detailed string representation of the TRUE element, which is 'TRUE'. ```python algebra = BooleanAlgebra() repr(algebra.TRUE) ``` -------------------------------- ### TRUE Element String Representation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Get the standard string representation of the TRUE element, which is '1'. ```python algebra = BooleanAlgebra() str(algebra.TRUE) ``` -------------------------------- ### Create Multiple Boolean Algebras Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Illustrates creating multiple BooleanAlgebra instances, including a standard one and a custom one with specific allowed token characters. It highlights that each algebra has its own TRUE/FALSE singletons and warns against mixing expressions from different algebras. ```python # Standard algebra std_algebra = BooleanAlgebra() # Custom algebra for domain-specific use custom_algebra = BooleanAlgebra(allowed_in_token=('.', ':', '_', '-')) # Each has its own TRUE/FALSE singletons std_true = std_algebra.TRUE custom_true = custom_algebra.TRUE std_true is custom_true # False (different algebras) std_true == custom_true # True (values are equal) # Cross-algebra mixing can cause issues a = std_algebra.Symbol('a') b = custom_algebra.Symbol('b') try: expr = a & b # May fail or behave unexpectedly except: print("Cannot mix expressions from different algebras") ``` -------------------------------- ### Run Main Tests Source: https://github.com/bastikr/boolean.py/wiki/Development Execute the main test suite for the project. This command is run from the project's root directory. ```bash python setup.py test ``` -------------------------------- ### Get Expression Hash Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Returns the hash value of an expression. Expressions are hashable and can be used in sets and as dictionary keys. ```python expr1 = algebra.parse('a and b') expr2 = algebra.parse('a and b') s = {expr1, expr2} len(s) # Likely 1 if structurally equal ``` ```python d = {expr1: 'value'} d[expr2] = 'new_value' # Works if expr1 == expr2 ``` -------------------------------- ### Instantiate BooleanAlgebra and Access FALSE Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Demonstrates how to create a BooleanAlgebra instance and access its FALSE constant. ```python algebra = BooleanAlgebra(); false_val = algebra.FALSE ``` -------------------------------- ### Create and Parse Boolean Expressions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Demonstrates how to initialize a BooleanAlgebra object, parse expressions from strings, and build them programmatically using symbols. Includes simplification and conversion to CNF/DNF. ```python from boolean import BooleanAlgebra # Create algebra algebra = BooleanAlgebra() # Parse from string expr = algebra.parse('(a or b) and not c') # Or build programmatically a, b, c = algebra.symbols('a', 'b', 'c') expr2 = (a | b) & ~c # Simplify simplified = expr.simplify() # Convert to normal form cnf = algebra.cnf(expr) # Conjunctive normal form (AND of ORs) dnf = algebra.dnf(expr) # Disjunctive normal form (OR of ANDs) ``` -------------------------------- ### Create OR Expression using Operators and Instantiation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Demonstrates creating OR expressions using the '|' and '+' operators, direct instantiation, and combining with TRUE/FALSE constants. ```python a, b, c = algebra.symbols('a', 'b', 'c') # Using | operator expr1 = a | b expr2 = a | b | c # Using + operator expr3 = a + b # Direct instantiation expr4 = algebra.OR(a, b, c) expr5 = algebra.OR(a, algebra.AND(b, c)) # With TRUE/FALSE expr6 = a | algebra.TRUE # Simplifies to TRUE (annihilation) expr7 = a | algebra.FALSE # Simplifies to a (identity) ``` -------------------------------- ### Create Standard Boolean Algebra Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Initializes a BooleanAlgebra instance with all default settings, including standard TRUE/FALSE values and operators. ```python algebra = BooleanAlgebra() ``` -------------------------------- ### flatten() Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Flattens nested operations of the same type within a boolean expression. For example, A & (B & C) is simplified to A & B & C. ```APIDOC ## flatten() ### Description Flatten nested operations of the same type. For example, `A & (B & C)` becomes `A & B & C`. ### Returns Expression with nested operations flattened. ### Example ```python expr = algebra.AND(a, algebra.AND(b, c)) expr.flatten() # Returns: AND(a, b, c) expr2 = algebra.OR(a, algebra.OR(b, algebra.OR(c, d))) expr2.flatten() # Returns: OR(a, b, c, d) ``` ``` -------------------------------- ### Custom Tokenizer Implementation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Shows how to create a custom tokenizer by extending BooleanAlgebra and yielding custom Symbol instances as token types for predefined or custom keywords. ```python class CustomAlgebra(BooleanAlgebra): def tokenize(self, expr): # Yield custom Symbol instances as token types for word in expr.split(): if word == 'AND': yield TOKEN_AND, word, 0 elif word == 'always_true': # Custom predefined symbol yield self.Symbol('always_true'), word, 0 else: yield TOKEN_SYMBOL, word, 0 ``` -------------------------------- ### Import Paths for Boolean.py Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Shows different ways to import components from the boolean library. Includes standard usage, specific operations, token constants, and internal modules. ```python # Standard usage - recommended from boolean import BooleanAlgebra, Symbol, ParseError # Get specific operations from boolean import AND, OR, NOT # Get token constants from boolean import TOKEN_AND, TOKEN_OR, TOKEN_SYMBOL, TOKEN_TRUE, TOKEN_FALSE # Internal (less stable API) from boolean.boolean import ( _TRUE, _FALSE, BaseElement, Function, DualBase, PARSE_ERRORS, PARSE_UNKNOWN_TOKEN, # ... other error codes ) ``` -------------------------------- ### Build Boolean Expressions with Operators and Constructors Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Demonstrates creating boolean expressions using standard Python bitwise operators (&, |, ~) and explicit class constructors (AND, OR, NOT). Supports alternative syntax for multiplication and addition. ```python a, b, c = algebra.symbols('a', 'b', 'c') # Using operators expr1 = a & (b | c) expr2 = ~a | (b & c) expr3 = a * b + c # Alternative syntax # Using class constructors expr4 = algebra.AND(a, algebra.OR(b, c)) ``` -------------------------------- ### Substitute Constants and Evaluate Expressions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Demonstrates substituting constants into an expression and evaluating the expression with variable assignments. Simplification can be applied during substitution. ```python expr = algebra.parse('x and y or z') # Substitute constants expr2 = expr.subs({algebra.Symbol('x'): algebra.TRUE}, simplify=True) # Result: OR(algebra.Symbol('y'), algebra.Symbol('z')) # Evaluate with variable assignment result = expr(**{'x': True, 'y': False, 'z': True}) # Returns: True (since z is True) ``` -------------------------------- ### Custom Operator Classes Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Example of customizing the string representation of AND, OR, and NOT operations by defining custom classes for them. This allows for different operator symbols. ```python class MyAND(AND): def __init__(self, *args): super().__init__(*args) self.operator = ' AND ' # Custom operator symbol class MyOR(OR): def __init__(self, *args): super().__init__(*args) self.operator = ' OR ' class MyNOT(NOT): def __init__(self, arg1): super().__init__(arg1) self.operator = 'NOT ' algebra = BooleanAlgebra( AND_class=MyAND, OR_class=MyOR, NOT_class=MyNOT ) expr = algebra.parse('a and b or c') print(expr) # a AND b OR c ``` -------------------------------- ### Pretty-print BaseElement Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Use the pretty() method to get a formatted string representation of a base element. The debug parameter can include additional information. ```python algebra = BooleanAlgebra() print(algebra.TRUE.pretty()) # "TRUE" print(algebra.FALSE.pretty(debug=True)) # "FALSE" ``` -------------------------------- ### Initialize BooleanAlgebra Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Instantiate BooleanAlgebra with optional custom classes for TRUE, FALSE, Symbol, NOT, AND, OR, and allowed characters in symbol names. ```python algebra = BooleanAlgebra( TRUE_class=None, # Custom TRUE class FALSE_class=None, # Custom FALSE class Symbol_class=None, # Custom Symbol class NOT_class=None, # Custom NOT class AND_class=None, # Custom AND class OR_class=None, # Custom OR class allowed_in_token=(".", ":", "_"), # Chars in symbol names ) ``` -------------------------------- ### Get All Symbols in an Expression Source: https://github.com/bastikr/boolean.py/blob/master/docs/users_guide.md The `get_symbols` method returns a list of all symbols in an expression, including duplicates. Use this when the order or frequency of symbols matters. ```python >>> import boolean >>> algebra = boolean.BooleanAlgebra() >>> algebra.parse("x|y&(x|z)").get_symbols() [Symbol('x'), Symbol('y'), Symbol('x'), Symbol('z')] ``` -------------------------------- ### Define Custom Boolean Algebras Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Demonstrates how to create a custom BooleanAlgebra by subclassing existing operators (like AND) to change their string representation. This allows for customized output formatting. ```python # Define custom operations with different string representation class MyAND(AND): def __init__(self, *args): super().__init__(*args) self.operator = ' AND ' # Create custom algebra custom = BooleanAlgebra(AND_class=MyAND) expr = custom.parse('a and b or c') print(expr) # a AND b|c ``` -------------------------------- ### Flatten Nested OR Operations Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Use flatten() to simplify nested OR operations into a single level. For example, A | (B | C) becomes A | B | C. ```python expr2 = algebra.OR(a, algebra.OR(b, algebra.OR(c, d))) expr2.flatten() # Returns: OR(a, b, c, d) ``` -------------------------------- ### Custom Algebra with Alternative Operators Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Shows how to create a custom BooleanAlgebra instance with alternative operators for AND and OR. This is useful for specific syntax requirements or custom logic. ```python class CustomAND(AND): def __init__(self, *args): super().__init__(*args) self.operator = 'AND' class CustomOR(OR): def __init__(self, *args): super().__init__(*args) self.operator = 'OR' custom_algebra = BooleanAlgebra(AND_class=CustomAND, OR_class=CustomOR) expr = custom_algebra.parse('a AND b OR c') ``` -------------------------------- ### Flatten Nested AND Operations Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Use flatten() to simplify nested AND operations into a single level. For example, A & (B & C) becomes A & B & C. ```python expr = algebra.AND(a, algebra.AND(b, c)) expr.flatten() # Returns: AND(a, b, c) ``` -------------------------------- ### Generate Truth Tables Using Symbols Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md Shows how to generate all possible truth assignments for a set of symbols and evaluate an expression for each assignment, effectively creating a truth table. This involves using `itertools.product` to generate combinations of boolean values. ```python symbols = algebra.symbols('p', 'q', 'r') expr = algebra.parse('p and (q or r)') # Generate all possible truth assignments import itertools for values in itertools.product([True, False], repeat=len(symbols)): assignment = dict(zip(symbols, values)) result = expr(**{s.obj: val for s, val in assignment.items()}) print(f"{assignment} => {result}") ``` -------------------------------- ### Get Symbol String Representation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md The __str__ method returns the string representation of the symbol's identifier. This is useful for displaying symbols in a human-readable format. ```python __str__() -> str ``` ```python a = Symbol('a') str(a) # 'a' sym = Symbol(42) str(sym) # '42' sym2 = Symbol(('x', 'y')) str(sym2) # "('x', 'y')" ``` -------------------------------- ### Get Unique Symbols in an Expression Source: https://github.com/bastikr/boolean.py/blob/master/docs/users_guide.md The `symbols` attribute returns a set of all unique symbols present in a boolean expression. This is helpful for identifying all variables involved. ```python >>> import boolean >>> algebra = boolean.BooleanAlgebra() >>> algebra.parse("x|y&(x|z)").symbols {Symbol('y'), Symbol('x'), Symbol('z')} ``` -------------------------------- ### ParseError Constructor Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/errors.md Details on how to create and use the ParseError exception, including its parameters and their types. ```APIDOC ## ParseError Constructor ### Description Create a ParseError with details about the parsing failure. ### Parameters #### Path Parameters - **token_type** (int or None) - Optional - None - The token type that caused the error (TOKEN_* constant) - **token_string** (str) - Optional - "" - The original text of the problematic token - **position** (int) - Optional - -1 - Position in the input where error occurred (character offset or -1 if unknown) - **error_code** (int) - Optional - 0 - Error code identifying the specific problem (PARSE_* constant) ### Request Example ```python from boolean import ParseError, PARSE_INVALID_EXPRESSION # Create a ParseError manually (rarely needed) error = ParseError( error_code=PARSE_INVALID_EXPRESSION, token_string="", position=5 ) ``` ``` -------------------------------- ### Limit Tox to Specific Python Interpreter Source: https://github.com/bastikr/boolean.py/blob/master/docs/development_guide.md If tox encounters an InterpreterNotFound error, limit its execution to specific installed Python interpreters, such as Python 3.6. ```shell tox -e py36 ``` -------------------------------- ### Testing Boolean Algebra Elements Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BaseElements.md Demonstrates the correct way to test Boolean algebra elements. Direct coercion to Python booleans is not allowed; instead, use equality checks. ```python if algebra.TRUE: pass # Raises: TypeError: Cannot evaluate expression as a Python Boolean. # Instead, test equality: if algebra.TRUE == algebra.TRUE: pass ``` -------------------------------- ### Create Symbols with BooleanAlgebra and Direct Instantiation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md Demonstrates two ways to create Symbol objects: using the BooleanAlgebra instance's symbols() method or by directly instantiating the Symbol class. Symbols are used to build boolean expressions. ```python from boolean import BooleanAlgebra, Symbol algebra = BooleanAlgebra() # Create symbols via BooleanAlgebra a, b, c = algebra.symbols('a', 'b', 'c') # Or directly instantiate x = Symbol('x') y = Symbol('y') # Build expressions expr = a & (b | ~c) expr2 = x | y ``` -------------------------------- ### Allowed Characters in Tokens Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Configures additional characters that can be part of symbol identifiers, beyond standard alphanumerics and underscores. This example allows hyphens and '@' symbols. ```python # Allow hyphens and @ symbols in tokens algebra = BooleanAlgebra(allowed_in_token=(".", ":", "_", "-", "@")) expr = algebra.parse('user@domain.com and api-key:secret') print(expr.symbols) # {Symbol('user@domain.com'), Symbol('api-key:secret')} # Without hyphens allowed, 'api-key' would tokenize as separate tokens algebra2 = BooleanAlgebra(allowed_in_token=(".", ":", "_")) expr2 = algebra2.parse('api-key') # Raises ParseError or parses as 'api' minus 'key' ``` -------------------------------- ### Compare Boolean Expressions for Equality and Equivalence Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Expression.md Shows how to compare expressions for structural equality (which is false without simplification) and mathematical equivalence (true after simplification). ```python expr1 = algebra.parse('a and b or a and c', simplify=False) expr2 = algebra.parse('a and (b or c)', simplify=False) # Structural equality (false without simplification) expr1 == expr2 # False # Mathematical equivalence (true after simplification) expr1.simplify() == expr2.simplify() # True ``` -------------------------------- ### definition() Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Retrieves the algebra's configuration, returning a tuple of its core components: TRUE, FALSE, NOT, AND, OR, and Symbol. ```APIDOC ## definition() -> tuple ### Description Return the algebra's configuration of element and operation types. ### Returns `(TRUE, FALSE, NOT, AND, OR, Symbol)` tuple containing the algebra's configured classes/singletons. ### Example ```python true, false, not_op, and_op, or_op, sym = algebra.definition() ``` ``` -------------------------------- ### Usage of TOKEN_TYPES for Token Identification Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md Shows how to use the TOKEN_TYPES dictionary to get the string description of a token type ID, both for debugging and within custom tokenizers. ```python # For debugging or error messages token_type_id = TOKEN_AND description = TOKEN_TYPES[token_type_id] # "AND" # In custom tokenizers to identify token types token_tuple = (TOKEN_SYMBOL, 'var_name', 5) print(f"Token type: {TOKEN_TYPES[token_tuple[0]]}") ``` -------------------------------- ### Get Symbol Hash Value Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md The __hash__ method provides a hash value for a Symbol, allowing it to be used in sets and dictionaries. Symbols with equal identifiers will have the same hash. ```python __hash__() -> int ``` ```python a = Symbol('a') b = Symbol('a') c = Symbol('c') # Symbols with same identifiers have same hash hash(a) == hash(b) # True # Can use symbols as set/dict keys s = {a, b, c} len(s) # Likely 2 (a and b are equal) d = {a: 'first', c: 'third'} d[b] = 'changed' # Updates a's value since a == b ``` -------------------------------- ### BooleanAlgebra Class Methods Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Methods for initializing the BooleanAlgebra class and performing core operations like parsing, tokenizing, and creating symbols. ```APIDOC ## BooleanAlgebra Initialization ### Description Initializes a BooleanAlgebra instance with optional custom classes for TRUE, FALSE, Symbol, NOT, AND, and OR operations. Allows customization of allowed characters in symbol names. ### Parameters - **TRUE_class** (class, optional) - Custom class for TRUE values. - **FALSE_class** (class, optional) - Custom class for FALSE values. - **Symbol_class** (class, optional) - Custom class for Symbol instances. - **NOT_class** (class, optional) - Custom class for NOT operations. - **AND_class** (class, optional) - Custom class for AND operations. - **OR_class** (class, optional) - Custom class for OR operations. - **allowed_in_token** (tuple, optional) - Characters allowed in symbol names. Defaults to (".", ":", "_"). ### Example ```python algebra = BooleanAlgebra( TRUE_class=MyTrue, FALSE_class=MyFalse, allowed_in_token=(".",) ) ``` ## Parse Expressions ### Description Parses a string representation of a boolean expression into an expression object. ### Method `algebra.parse(expr_string, simplify=False)` ### Parameters - **expr_string** (str) - The string to parse. - **simplify** (bool, optional) - Whether to simplify the expression after parsing. Defaults to False. ### Returns - An expression object representing the parsed boolean expression. ### Example ```python expr = algebra.parse("a & (b | c)") ``` ## Tokenize Expression ### Description Tokenizes a string representation of a boolean expression. ### Method `algebra.tokenize(expr_string)` ### Parameters - **expr_string** (str) - The string to tokenize. ### Returns - A list of tokens representing the expression. ### Example ```python tokens = algebra.tokenize("a & b") ``` ## Create Symbols ### Description Creates one or more symbol objects. ### Method `algebra.symbols(*names)` ### Parameters - **names** (str) - One or more names for the symbols. ### Returns - A tuple of Symbol objects. ### Example ```python a, b, c = algebra.symbols('a', 'b', 'c') ``` ## Get Definition ### Description Retrieves the base definitions for TRUE, FALSE, NOT, AND, OR, and Symbol classes used by the algebra instance. ### Method `algebra.definition()` ### Returns - A tuple containing (TRUE_class, FALSE_class, NOT_class, AND_class, OR_class, Symbol_class). ### Example ```python true, false, not_op, and_op, or_op, sym_class = algebra.definition() ``` ## Normalize to Conjunctive Normal Form (CNF) ### Description Converts an expression to its Conjunctive Normal Form (CNF). ### Method `algebra.cnf(expr)` ### Parameters - **expr** (Expression) - The expression to convert. ### Returns - An expression in CNF. ### Example ```python cnf_expr = algebra.cnf(expr) ``` ## Normalize to Disjunctive Normal Form (DNF) ### Description Converts an expression to its Disjunctive Normal Form (DNF). ### Method `algebra.dnf(expr)` ### Parameters - **expr** (Expression) - The expression to convert. ### Returns - An expression in DNF. ### Example ```python dnf_expr = algebra.dnf(expr) ``` ## Generic Normalization ### Description Normalizes an expression into a specified operator form (e.g., AND for CNF, OR for DNF). ### Method `algebra.normalize(expr, operator)` ### Parameters - **expr** (Expression) - The expression to normalize. - **operator** (class) - The target operator class (e.g., `algebra.AND`). ### Returns - A normalized expression. ### Example ```python normalized_expr = algebra.normalize(expr, algebra.AND) ``` ``` -------------------------------- ### Simplify Boolean Expressions Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Operations.md Demonstrates simplification of boolean expressions using distributive, absorption, and complementation laws. The simplify() method applies these algebraic rules. ```python # Distributive property expr = algebra.parse('(a | b) & (c | d)') simplified = expr.simplify() # May become: OR(AND(a,c), AND(a,d), AND(b,c), AND(b,d)) # Absorption expr2 = algebra.parse('a & (a | b)') expr2.simplify() # Returns: Symbol('a') # Complementation expr3 = algebra.parse('a | ~a') expr3.simplify() # Returns: TRUE (law of excluded middle) expr4 = algebra.parse('a & ~a') expr4.simplify() # Returns: FALSE (contradiction) ``` -------------------------------- ### Get Sub-Terms of an Expression Source: https://github.com/bastikr/boolean.py/blob/master/docs/users_guide.md Use the `args` property to retrieve a tuple of terms within a boolean expression. This is useful for breaking down complex expressions into their constituent parts. ```python >>> import boolean >>> algebra = boolean.BooleanAlgebra() >>> algebra.parse("x|y|z").args (Symbol('x'), Symbol('y'), Symbol('z')) ``` -------------------------------- ### Parse and Simplify Boolean Expressions (Python) Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Demonstrates parsing a boolean expression and then simplifying it using absorption laws. Ensure BooleanAlgebra is imported. ```python from boolean import BooleanAlgebra algebra = BooleanAlgebra() # Parse expr = algebra.parse('a and (a or b)', simplify=False) print(expr) # a&(a|b) # Simplify (applies absorption law) simplified = expr.simplify() print(simplified) # a ``` -------------------------------- ### Get Symbol Debug Representation Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md The __repr__ method provides a detailed string representation of the Symbol object, primarily for debugging purposes. It typically shows how to recreate the object. ```python __repr__() -> str ``` ```python a = Symbol('a') repr(a) # "Symbol('a')" sym = Symbol(42) repr(sym) # "Symbol(42)" # Useful in REPL and debugging symbols = [Symbol('x'), Symbol('y')] print(symbols) # [Symbol('x'), Symbol('y')] ``` -------------------------------- ### Work with Boolean Expression Content Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Shows how to extract symbols and literals from an expression, apply substitutions, and evaluate the expression's truth value given a truth assignment. ```python # Extract symbols symbols = expr.symbols # Set of all Symbol instances symbol_names = {s.obj for s in expr.symbols} # Extract literals (including negations) literals = expr.literals # Set with NOT(Symbol) instances # Apply substitution result = expr.subs({a: algebra.TRUE}, simplify=True) # Evaluate with truth assignment value = expr(a=True, b=False, c=True) # Returns bool ``` -------------------------------- ### Evaluate Boolean Expressions with Variables (Python) Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/README.md Illustrates how to evaluate a boolean expression by providing values for its variables. The expression is evaluated based on the truthiness of the provided keyword arguments. ```python expr = algebra.parse('(user_logged_in and not admin) or super_user') # Evaluate result = expr(user_logged_in=True, admin=False, super_user=False) # True result = expr(user_logged_in=False, admin=False, super_user=True) # True result = expr(user_logged_in=False, admin=True, super_user=False) # False ``` -------------------------------- ### Create Default BooleanAlgebra Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Instantiate the default BooleanAlgebra. This is useful for standard boolean operations without custom configurations. ```python from boolean import BooleanAlgebra algebra = BooleanAlgebra() ``` -------------------------------- ### Custom String Representation for Operators Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Defines custom classes for AND, OR, and NOT operators to change their string representation, then initializes BooleanAlgebra with these custom classes. The example demonstrates parsing an expression and printing its custom string representation. ```python class CustomAND(AND): def __init__(self, *args): super().__init__(*args) self.operator = ' ∧ ' # Mathematical AND symbol class CustomOR(OR): def __init__(self, *args): super().__init__(*args) self.operator = ' ∨ ' # Mathematical OR symbol class CustomNOT(NOT): def __init__(self, arg1): super().__init__(arg1) self.operator = '¬' # Mathematical NOT symbol algebra = BooleanAlgebra( AND_class=CustomAND, OR_class=CustomOR, NOT_class=CustomNOT ) expr = algebra.parse('a and b or not c') print(expr) # a ∧ b ∨ ¬c ``` -------------------------------- ### symbols(*args) Source: https://github.com/bastikr/boolean.py/blob/master/docs/api/boolean.md Creates one or more symbol objects. ```APIDOC ## symbols(*args) ### Description Return a tuple of symbols building a new Symbol from each argument. ### Parameters - **args** (strings) - Required - One or more arguments to create symbols from. ``` -------------------------------- ### DualBase Class Methods Source: https://github.com/bastikr/boolean.py/blob/master/docs/api/modules.md Provides methods for simplifying and manipulating dual expressions. ```APIDOC ## DualBase.absorb() ### Description Applies the absorption law. ### Method `DualBase.absorb()` ### Parameters None ### Response Returns the expression after applying absorption. ``` ```APIDOC ## DualBase.distributive() ### Description Applies the distributive law. ### Method `DualBase.distributive()` ### Parameters None ### Response Returns the expression after applying the distributive law. ``` ```APIDOC ## DualBase.flatten() ### Description Flattens nested operations. ### Method `DualBase.flatten()` ### Parameters None ### Response Returns the flattened expression. ``` ```APIDOC ## DualBase.simplify() ### Description Simplifies the dual expression. ### Method `DualBase.simplify()` ### Parameters None ### Response Returns the simplified dual expression. ``` ```APIDOC ## DualBase.subtract() ### Description Performs subtraction on the dual expression. ### Method `DualBase.subtract()` ### Parameters None ### Response Returns the result of the subtraction. ``` -------------------------------- ### Symbol Object Type Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/types.md The `obj` parameter of the Symbol constructor accepts any hashable type. Examples demonstrate valid inputs like strings, integers, tuples, and frozensets. Unhashable types like lists and dictionaries are commented out as they would raise a TypeError. ```python # All valid Symbol('name') # String Symbol(42) # Integer Symbol(('a', 'b')) # Tuple Symbol(('user', 'admin')) # Nested tuple Symbol(frozenset([1,2])) # Frozenset # Not valid (unhashable) # Symbol(['a', 'b']) # List would raise TypeError # Symbol({'key': 'val'}) # Dict would raise TypeError ``` -------------------------------- ### pretty(indent=0, debug=False) Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/Symbol.md Returns a pretty-formatted string representation of the symbol, with options for indentation and including debug information. ```APIDOC ## pretty(indent=0, debug=False) ### Description Return a pretty-formatted representation of the symbol as a string. ### Method Signature `pretty(indent=0, debug=False) -> str` ### Parameters #### Optional Parameters - **indent** (int) - Default: 0 - Number of spaces for indentation. - **debug** (bool) - Default: False - If True, include debug information (isliteral, iscanonical). ### Returns - `str` — Formatted string representation. ### Example ```python a = Symbol('a') print(a.pretty()) # "Symbol('a')" print(a.pretty(indent=4, debug=True)) # " Symbol('a')" ``` ``` -------------------------------- ### Test Custom Algebra Configuration Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/configuration.md Verify that custom BooleanAlgebra configurations, including custom symbol classes, function as expected for parsing, evaluation, and string representation. ```python def test_custom_algebra(): algebra = BooleanAlgebra(Symbol_class=MySymbol) # Test parsing expr = algebra.parse('a and b') assert isinstance(expr.args[0], MySymbol) # Test evaluation result = expr(a=True, b=False) assert result is False # Test string representation assert str(expr.args[0]) == 'A' # MySymbol uppercase ``` -------------------------------- ### Custom Algebra with Custom Tokenizer Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/api-reference/BooleanAlgebra.md Illustrates how to subclass BooleanAlgebra to implement custom tokenization logic. This allows for parsing expressions with non-standard operators or symbols. ```python class CustomAlgebra(BooleanAlgebra): def tokenize(self, expr): # Custom tokenization logic ops = {'⋀': TOKEN_AND, '⋁': TOKEN_OR, '¬': TOKEN_NOT} # ... yield custom tokens ``` -------------------------------- ### Custom Tokenizer Configuration Source: https://github.com/bastikr/boolean.py/blob/master/_autodocs/INDEX.txt The BooleanAlgebra constructor accepts options for custom tokenization. This allows defining specific patterns for operators, symbols, and other elements. ```python from boolean import BooleanAlgebra # Define custom token patterns custom_tokens = { 'AND': '&', 'OR': '|', 'NOT': '~', 'LPAREN': '(', 'RPAREN': ')', 'SYMBOL': '[a-zA-Z]+' } # Instantiate BooleanAlgebra with custom tokenizer algebra = BooleanAlgebra(tokenizer_patterns=custom_tokens) # Parse expressions using the custom tokenizer expr = algebra.parse("my_symbol & another_symbol") ```