### Evaluate Simple Expression Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use simple_eval to evaluate basic arithmetic expressions. No additional setup is required for standard operations. ```python from simpleeval import simple_eval simple_eval("21 + 21") ``` -------------------------------- ### Block Private Module Attributes Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Private attributes (starting with `_`) and methods in `DISALLOW_METHODS` are always blocked, even when using `ModuleWrapper`. This prevents access to internal implementation details. ```python >>> s = SimpleEval(names={'path': ModuleWrapper(os.path)}) >>> s.eval("path.__file__") ``` -------------------------------- ### Configure SimpleEval Instance During Creation Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Initialize `SimpleEval` with custom functions by passing a dictionary to the `functions` parameter during instantiation. ```python def boo(): return 'Boo!' s = SimpleEval(functions={"boo": boo}) ``` -------------------------------- ### Create and Use SimpleEval Instance Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Instantiate `SimpleEval` for repeated evaluations. This can improve performance by parsing expressions only once. ```pycon >>> s = SimpleEval() >>> s.eval("1 + 1") 2 >>> s.eval('100 * 10') 1000 ``` -------------------------------- ### Customizing Operators in SimpleEval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Shows how to replace default operators like XOR with power, use unlimited power calculations, define custom division that handles zero division, and disable operators entirely. ```python import ast import operator from simpleeval import SimpleEval, safe_power, DEFAULT_OPERATORS # Replace ^ (bitwise XOR) with power operator s = SimpleEval() s.operators[ast.BitXor] = safe_power result = s.eval("3 ^ 2") # Now means 3 ** 2 # Output: 9 result = s.eval("2 ^ 10") # Now means 2 ** 10 # Output: 1024 # Remove power limits for trusted environments s = SimpleEval() s.operators[ast.Pow] = operator.pow # Use unlimited power result = s.eval("2 ** 100") # Output: 1267650600228229401496703205376 # Create custom operators def safe_divide(a, b): """Division that returns None instead of raising ZeroDivisionError""" if b == 0: return None return a / b s = SimpleEval() s.operators[ast.Div] = safe_divide result = s.eval("10 / 0") # Output: None result = s.eval("10 / 2") # Output: 5.0 # Disable specific operators s = SimpleEval() del s.operators[ast.Pow] # Remove power operator entirely try: s.eval("2 ** 10") except Exception as e: print(f"Operator disabled: {e}") # Output: Operator disabled: Sorry, Pow is not available in this evaluator ``` -------------------------------- ### Optimize SimpleEval with Pre-parsed Expressions Source: https://context7.com/danthedeckie/simpleeval/llms.txt For performance, parse an expression once using `s.parse()` and then evaluate it multiple times with different `names`. This avoids repeated parsing overhead. ```python # Parse once, evaluate multiple times (performance optimization) expression = "x * y + z" parsed = s.parse(expression) for values in [{"x": 1, "y": 2, "z": 3}, {"x": 10, "y": 20, "z": 30}]: s.names = values print(s.eval(expression, previously_parsed=parsed)) # Output: 5 # Output: 230 ``` -------------------------------- ### Basic Usage of SimpleEval Class Source: https://context7.com/danthedeckie/simpleeval/llms.txt Instantiate `SimpleEval` for reusable evaluation configurations. This is more efficient for multiple evaluations with the same settings. ```python from simpleeval import SimpleEval # Create a reusable evaluator s = SimpleEval() # Basic usage print(s.eval("20 + 30 - (10 * 5)")) # Output: 0 print(s.eval("2 ** 10")) # Output: 1024 print(s.eval("100 % 9")) # Output: 1 ``` -------------------------------- ### Viewing Security Configuration Constants Source: https://context7.com/danthedeckie/simpleeval/llms.txt Display default limits and disallowed elements configured in simpleeval, such as comprehension length, shift limits, prefixes, methods, and functions. ```python # Comprehension limits (for EvalWithCompoundTypes) print(f"Default MAX_COMPREHENSION_LENGTH: {simpleeval.MAX_COMPREHENSION_LENGTH}") # 10000 # Shift operation limits print(f"Default MAX_SHIFT: {simpleeval.MAX_SHIFT}") # 10000 # View disallowed prefixes and methods print(f"DISALLOW_PREFIXES: {simpleeval.DISALLOW_PREFIXES}") # Output: ['_', 'func_'] print(f"DISALLOW_METHODS: {simpleeval.DISALLOW_METHODS}") # Output: ['format', 'format_map', 'mro', ...] # View disallowed functions print(f"DISALLOW_FUNCTIONS contains: type, eval, exec, open, getattr, ...") # These are blocked even if passed to the evaluator ``` -------------------------------- ### Using BASIC_ALLOWED_ATTRS for Safe Attribute Access Source: https://context7.com/danthedeckie/simpleeval/llms.txt Demonstrates using BASIC_ALLOWED_ATTRS to safely access attributes and methods on strings, numbers, dictionaries, and lists. Also shows how to extend allowed attributes for custom classes and how disallowed access is blocked. ```python from simpleeval import simple_eval, SimpleEval, BASIC_ALLOWED_ATTRS, FeatureNotAvailable # Using BASIC_ALLOWED_ATTRS for safer evaluation result = simple_eval("' hello world '.strip().upper()", allowed_attrs=BASIC_ALLOWED_ATTRS) # Output: 'HELLO WORLD' result = simple_eval("'hello,world,python'.split(',')", allowed_attrs=BASIC_ALLOWED_ATTRS) # Output: ['hello', 'world', 'python'] # Integer and float methods result = simple_eval("(255).to_bytes(2, 'big')", allowed_attrs=BASIC_ALLOWED_ATTRS) # Output: b'\x00\xff' result = simple_eval("(3.14159).is_integer()", allowed_attrs=BASIC_ALLOWED_ATTRS) # Output: False # Dictionary and list methods result = simple_eval("{'a': 1, 'b': 2}.get('c', 'default')", allowed_attrs=BASIC_ALLOWED_ATTRS) # Output: 'default' # Extending with custom class attributes class Product: def __init__(self, name, price): self.name = name self.price = price def discounted_price(self, discount): return self.price * (1 - discount) extended_attrs = BASIC_ALLOWED_ATTRS.copy() extended_attrs[Product] = {"name", "price", "discounted_price"} product = Product("Widget", 29.99) result = simple_eval( "item.discounted_price(0.1)", names={"item": product}, allowed_attrs=extended_attrs ) # Output: 26.991 # Blocking access to non-whitelisted attributes try: result = simple_eval( "item.price.__class__", names={"item": product}, allowed_attrs=extended_attrs ) except FeatureNotAvailable as e: print(f"Blocked: {e}") # Output: Blocked: Sorry, attribute access not allowed on '' ``` -------------------------------- ### Viewing and Modifying MAX_POWER Limit Source: https://context7.com/danthedeckie/simpleeval/llms.txt Inspect the default MAX_POWER limit and reduce it to enforce stricter computational limits. Demonstrates exceeding the reduced limit. ```python import simpleeval from simpleeval import SimpleEval, simple_eval # View and modify power limits print(f"Default MAX_POWER: {simpleeval.MAX_POWER}") # 4000000 # Reduce limit for more restrictive environment simpleeval.MAX_POWER = 1000 try: simple_eval("2 ** 1001") except simpleeval.NumberTooHigh: print("Power limit exceeded") # Output: Power limit exceeded simpleeval.MAX_POWER = 4000000 # Reset to default ``` -------------------------------- ### Define and Use Custom Functions in SimpleEval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Enable domain-specific operations by defining custom functions. These can be lambdas, regular functions, or functions with default arguments. Ensure functions are passed in the 'functions' dictionary. ```python import simpleeval from simpleeval import SimpleEval, simple_eval # Lambda functions result = simple_eval("double(21)", functions={"double": lambda x: x * 2}) # Output: 42 ``` ```python # Regular functions with multiple arguments def calculate_compound_interest(principal, rate, years): return principal * (1 + rate) ** years result = simple_eval( "calculate_compound_interest(1000, 0.05, 10)", functions={"calculate_compound_interest": calculate_compound_interest} ) # Output: 1628.894626777442 ``` ```python # Functions with default arguments def greet(name, greeting="Hello"): return f"{greeting}, {name}!" result = simple_eval('greet("World")', functions={"greet": greet}) # Output: 'Hello, World!' result = simple_eval('greet("World", greeting="Hi")', functions={"greet": greet}) # Output: 'Hi, World!' ``` ```python # Extending default functions my_functions = simpleeval.DEFAULT_FUNCTIONS.copy() my_functions.update({ "abs": abs, "min": min, "max": max, "len": len, "sum": sum, }) result = simple_eval("max(abs(-5), min(10, 20)) + randint(1)", functions=my_functions) # Output: 10 + random_int (10-10 based on randint behavior) ``` ```python # File reading function example def read_config(key): config = {"debug": True, "max_retries": 3, "timeout": 30} return config.get(key, None) s = SimpleEval(functions={"config": read_config}) result = s.eval('config("timeout") * 2') # Output: 60 ``` -------------------------------- ### Evaluate Expressions with Custom Functions using simple_eval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Define and use custom functions by passing them as a dictionary to the `functions` parameter. Functions should be Python callables. ```python # Using custom functions result = simple_eval("square(11) + cube(3)", functions={"square": lambda x: x*x, "cube": lambda x: x**3}) # Output: 148 ``` -------------------------------- ### Create and Access Dictionaries with EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Construct dictionaries and access their values using keys within expressions. Supports standard Python dictionary literal syntax and key access. ```python # Create dictionaries result = s.eval('{"name": "Alice", "age": 30}') # Output: {'name': 'Alice', 'age': 30} result = s.eval('{"scores": [85, 90, 78]}["scores"][1]') # Output: 90 ``` -------------------------------- ### Safe Module Access with ModuleWrapper Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use `ModuleWrapper` to safely expose modules like `os.path`. It enforces restrictions on dangerous methods and private attributes by default. ```python >>> from simpleeval import SimpleEval, ModuleWrapper >>> import os.path >>> s = SimpleEval(names={'path': ModuleWrapper(os.path)}) >>> s.eval("path.exists('/etc/passwd')") ``` -------------------------------- ### Manage Custom Names (Variables) in SimpleEval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Provide variables for expressions to reference using dictionaries or callable functions. Callable names allow for dynamic value resolution. ```python from simpleeval import SimpleEval, simple_eval, NameNotDefined # Simple dictionary names result = simple_eval("a + b * c", names={"a": 10, "b": 5, "c": 2}) # Output: 20 ``` ```python # Nested dictionary access with dot notation result = simple_eval("user.name", names={"user": {"name": "Alice", "age": 30}}) # Output: 'Alice' ``` ```python # Using callable names for dynamic lookups def dynamic_lookup(node): """Look up values from a database or external source""" values = { "temperature": 72.5, "humidity": 45, "pressure": 1013.25, } if node.id in values: return values[node.id] raise NameNotDefined(node.id, "Variable not found") result = simple_eval("temperature > 70 and humidity < 50", names=dynamic_lookup) # Output: True ``` ```python # Combining static and dynamic names with function fallback s = SimpleEval() s.names = {"base_value": 100} s.functions = {"multiplier": 2} # Functions can act as name fallback # When 'multiplier' is not found in names, it falls back to functions result = s.eval("base_value * multiplier") # Output: 200 ``` ```python # Preserving default names (True, False, None) from simpleeval import DEFAULT_NAMES my_names = DEFAULT_NAMES.copy() my_names.update({"x": 10, "y": 20}) result = simple_eval("x > 5 and True", names=my_names) # Output: True ``` -------------------------------- ### Enable Basic Allowed Attributes Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use `BASIC_ALLOWED_ATTRS` to enable a set of safe, default attribute access. This is recommended for most use cases and will be the default in version 2.x. ```python >>> from simpleeval import simpleeval, BASIC_ALLOWED_ATTRS >>> simpleeval("' hello '.strip()", allowed_attrs=BASIC_ALLOWED_ATTRS) ``` -------------------------------- ### Extending SimpleEval Class for Custom Behavior Source: https://context7.com/danthedeckie/simpleeval/llms.txt Illustrates subclassing SimpleEval to create evaluators that disallow method calls and evaluators that log all expressions and their results. ```python import ast from simpleeval import SimpleEval, FeatureNotAvailable, EvalWithCompoundTypes # Evaluator that disallows method calls class EvalNoMethods(SimpleEval): """Evaluator that blocks all method calls on objects""" def _eval_call(self, node): if isinstance(node.func, ast.Attribute): raise FeatureNotAvailable("Method calls are not allowed") return super()._eval_call(node) s = EvalNoMethods() s.functions["len"] = len result = s.eval("len('hello')") # Function call: OK # Output: 5 try: s.eval("'hello'.upper()") # Method call: blocked except FeatureNotAvailable as e: print(f"Blocked: {e}") # Output: Blocked: Method calls are not allowed # Evaluator with logging class LoggingEval(SimpleEval): """Evaluator that logs all evaluations""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.log = [] def eval(self, expr, previously_parsed=None): result = super().eval(expr, previously_parsed) self.log.append({"expression": expr, "result": result}) return result s = LoggingEval() s.eval("10 + 20") s.eval("5 * 5") print(s.log) # Output: [{'expression': '10 + 20', 'result': 30}, {'expression': '5 * 5', 'result': 25}] ``` -------------------------------- ### Evaluate Cached Parse Tree with Different Names Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Parse an expression once and evaluate it multiple times with varying `names` by assigning to `s.names`. This optimizes performance for repeated evaluations of the same expression. ```python # Set up & Cache the parse tree: expression = "foo + bar" parsed = s.parse(expression) # evaluate the expression multiple times: for names in [{"foo": 1, "bar": 10}, {"foo": 100, "bar": 42}]: s.names = names print(s.eval(expression, previously_parsed=parsed)) ``` -------------------------------- ### Create and Access Lists with EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Use `EvalWithCompoundTypes` to create lists within expressions and access their elements by index. Supports standard Python list syntax. ```python from simpleeval import EvalWithCompoundTypes s = EvalWithCompoundTypes() # Create and manipulate lists result = s.eval("[1, 2, 3, 4, 5]") # Output: [1, 2, 3, 4, 5] result = s.eval("[1, 2, 3][1]") # Output: 2 ``` -------------------------------- ### Configure SimpleEval with Custom Names Source: https://context7.com/danthedeckie/simpleeval/llms.txt Define custom variables by adding them to the evaluator's `names` dictionary. These variables are then available for use in expressions. ```python # Configure with custom names (variables) s.names["user_score"] = 85 s.names["bonus"] = 15 print(s.eval("user_score + bonus")) # Output: 100 ``` -------------------------------- ### Evaluate Dictionary Comprehensions with EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Enables the creation of dictionaries using comprehension syntax, mapping keys to values based on an iterable. Supports transformations and conditions. ```python # Dictionary comprehensions result = s.eval("{x: x**2 for x in [1, 2, 3, 4]}") # Output: {1: 1, 2: 4, 3: 9, 4: 16} ``` -------------------------------- ### Access Dictionary Keys with Dot Notation Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Evaluate expressions that access dictionary keys using dot notation (e.g., `foo.bar`). This feature is enabled by default and can be disabled. ```pycon >>> simple_eval("foo.bar", names={"foo": {"bar": 42}}) 42 ``` -------------------------------- ### Define and Use Custom Functions Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Define custom functions to be used within evaluated expressions. This allows for extending the functionality available to simpleeval. ```pycon >>> simple_eval("double(21)", functions={"double": lambda x:x*2}) 42 ``` ```python >>> def double(x): ... return x * 2 >>> simple_eval("d(100) + double(1)", functions={"d": double, "double":double}) 202 ``` -------------------------------- ### Replace Bitwise XOR with Safe Power Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use this to replace the default bitwise XOR operator with a safe power function, allowing expressions like '3 ^ 2' to evaluate to 9. ```pycon >>> import ast >>> from simpleeval import safe_power >>> s = SimpleEval() >>> s.operators[ast.BitXor] = safe_power >>> s.eval("3 ^ 2") 9 ``` -------------------------------- ### Evaluate Conditional Expressions with simple_eval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Supports Python-like conditional expressions (ternary operator) for evaluating different outcomes based on a condition. Requires names to be defined if used in the condition. ```python # Conditional expressions result = simple_eval("'adult' if age >= 18 else 'minor'", names={"age": 25}) # Output: 'adult' ``` -------------------------------- ### Handling FeatureNotAvailable Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch FeatureNotAvailable when attempting to use blocked features like 'import'. ```python # FeatureNotAvailable - trying to use blocked features try: simple_eval("import os") except FeatureNotAvailable as e: print(f"Feature blocked: {e}") # Output: Feature blocked: Sorry, 'import' is not allowed. ``` -------------------------------- ### Secure Module Access with ModuleWrapper in SimpleEval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Control access to Python modules within expressions using ModuleWrapper. Specify allowed attributes to restrict access for security. ```python import os.path import math from simpleeval import SimpleEval, ModuleWrapper # Basic module wrapping s = SimpleEval(names={"path": ModuleWrapper(os.path)}) result = s.eval("path.exists('/etc/passwd')") # Output: True (on Linux) or False (on Windows) result = s.eval("path.join('home', 'user', 'documents')") # Output: 'home/user/documents' (or 'home\user\documents' on Windows) ``` ```python # Restricted module access with whitelist s = SimpleEval(names={ "path": ModuleWrapper(os.path, allowed_attrs={"exists", "join", "basename"}) }) result = s.eval("path.basename('/home/user/file.txt')") # Output: 'file.txt' # This will raise FeatureNotAvailable because 'dirname' is not in allowed_attrs try: s.eval("path.dirname('/home/user/file.txt')") except Exception as e: print(f"Error: {e}") # Output: Error: Access to 'dirname' is not allowed on this wrapped module ``` ```python # Wrapping math module for scientific calculations s = SimpleEval(names={ "math": ModuleWrapper(math, allowed_attrs={"sqrt", "sin", "cos", "pi", "e"}) }) result = s.eval("math.sqrt(16) + math.pi") # Output: 7.141592653589793 result = s.eval("math.sin(math.pi / 2)") # Output: 1.0 ``` ```python # Private attributes are always blocked try: s.eval("path.__file__") except Exception as e: print(f"Blocked: {e}") # Output: Blocked: Access to private attribute '__file__' is not allowed ``` -------------------------------- ### Disable Attribute-Index Fallback Source: https://context7.com/danthedeckie/simpleeval/llms.txt Demonstrates disabling the attribute-index fallback mechanism. When disabled, dictionary access must use bracket notation (e.g., data['key']) instead of dot notation (e.g., data.key). ```python s = SimpleEval() print(f"Default ATTR_INDEX_FALLBACK: {s.ATTR_INDEX_FALLBACK}") # True s.ATTR_INDEX_FALLBACK = False s.names = {"data": {"key": "value"}} # With fallback disabled, this will fail try: s.eval("data.key") except simpleeval.AttributeDoesNotExist: print("Must use data['key'] syntax") ``` -------------------------------- ### Configure SimpleEval with Custom Functions Source: https://context7.com/danthedeckie/simpleeval/llms.txt Add custom Python functions to the evaluator's `functions` dictionary. These can then be called within expressions evaluated by this instance. ```python def calculate_tax(amount, rate=0.1): return amount * rate s.functions["tax"] = calculate_tax s.functions["round"] = round print(s.eval("round(tax(99.99, 0.0825), 2)")) # Output: 8.25 ``` -------------------------------- ### Evaluate Expression with Names Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use the `names` parameter to provide variables for expression evaluation. This is useful when expressions depend on external data. ```pycon >>> simple_eval("a + b", names={"a": 11, "b": 100}) 111 ``` -------------------------------- ### Custom Attribute Allowlist for Classes Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Define custom attribute access rules for specific classes by copying `BASIC_ALLOWED_ATTRS` and adding class-specific dictionaries. This allows fine-grained control over which attributes can be accessed. ```python >>> from simpleeval import simpleeval, BASIC_ALLOWED_ATTRS >>> class Foo: >>> bar = 42 >>> hidden = "secret" >>> >>> our_attributes = BASIC_ALLOWED_ATTRS.copy() >>> our_attributes[Foo] = {'bar'} >>> simpleeval("foo.bar", names={\"foo\": Foo()}, allowed_attrs=our_attributes) ``` ```python >>> simpleeval("foo.hidden", names={\"foo\": Foo()}, allowed_attrs=our_attributes) ``` -------------------------------- ### Comprehensive Safe Evaluation Pattern Source: https://context7.com/danthedeckie/simpleeval/llms.txt Implement a robust evaluation function that handles various simpleeval exceptions, returning structured success or error information. ```python # Comprehensive error handling pattern def safe_evaluate(expression, **kwargs): """Safely evaluate an expression with comprehensive error handling""" try: return {"success": True, "result": simple_eval(expression, **kwargs)} except (FunctionNotDefined, NameNotDefined) as e: return {"success": False, "error": "undefined", "message": str(e)} except FeatureNotAvailable as e: return {"success": False, "error": "forbidden", "message": str(e)} except (NumberTooHigh, IterableTooLong) as e: return {"success": False, "error": "resource_limit", "message": str(e)} except InvalidExpression as e: return {"success": False, "error": "syntax", "message": str(e)} except Exception as e: return {"success": False, "error": "unknown", "message": str(e)} print(safe_evaluate("10 + 20")) # Output: {'success': True, 'result': 30} print(safe_evaluate("undefined()")) # Output: {'success': False, 'error': 'undefined', 'message': "Function 'undefined' not defined..."} ``` -------------------------------- ### Evaluate Complex Expressions with simple_eval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Handles complex mathematical expressions involving multiple operators and precedence rules. Ensure all operators used are supported by default or explicitly allowed. ```python # Complex expressions with operators result = simple_eval("21 + 19 / 7 + (8 % 3) ** 9") # Output: 535.7142857142857 ``` -------------------------------- ### Extend Default Functions Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Extend the default functions provided by simpleeval by copying the default dictionary and updating it with new functions. This allows retaining built-in functions while adding custom ones. ```pycon >>> my_functions = simpleeval.DEFAULT_FUNCTIONS.copy() >>> my_functions.update( ... square=(lambda x:x*x), ... double=(lambda x:x+x), ... ) >>> simple_eval('square(randint(100))', functions=my_functions) ``` -------------------------------- ### Name Handler with Exception Handling Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Implement a name handler that raises `NameNotDefined` when a variable is not found. This allows for controlled error handling during evaluation. ```pycon >>> def name_handler(node): ... if node.id[0] == 'a': ... return 21 ... raise NameNotDefined(node.id[0], "Not found") ... ... simple_eval('a + a', names=name_handler, functions={"b": 100}) 42 ``` ```pycon >>> simple_eval('a + b', names=name_handler, functions={'b': 100}) 121 ``` -------------------------------- ### Evaluate Expressions with Custom Variables using simple_eval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Pass custom variables as a dictionary to the `names` parameter for use within the expression. This allows dynamic calculation based on provided data. ```python # Using custom variables (names) result = simple_eval("price * quantity * (1 - discount)", names={"price": 10.99, "quantity": 5, "discount": 0.15}) # Output: 46.7075 ``` -------------------------------- ### Use Tuples and Sets with EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Evaluate expressions involving tuple concatenation and set literals. Duplicates are automatically handled in sets. ```python # Tuples and sets result = s.eval("(1, 2) + (3, 4)") # Output: (1, 2, 3, 4) result = s.eval("{1, 2, 2, 3, 3, 3}") # Output: {1, 2, 3} ``` -------------------------------- ### Disable All Attribute Access Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Use an empty dictionary for `allowed_attrs` to disable all attribute access. This will raise a `FeatureNotAvailable` error for any attribute access. ```python >>> simpleeval("' hello '.strip()", allowed_attrs={}) ``` -------------------------------- ### Using Built-in Functions with Comprehensions in EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Integrate standard Python built-in functions like `sum` and `range` within comprehension expressions. Ensure these functions are available or added to `s.functions`. ```python # Using built-in functions with comprehensions s.functions["sum"] = sum s.functions["range"] = range result = s.eval("sum([x**2 for x in range(5)])") # Output: 30 ``` -------------------------------- ### Evaluate String Operations with simple_eval Source: https://context7.com/danthedeckie/simpleeval/llms.txt Allows string manipulation, including method calls like `.upper()` and concatenation. Ensure string methods used are safe and whitelisted. ```python # String operations result = simple_eval("name.upper() + '!' * 3", names={"name": "hello"}) # Output: 'HELLO!!!' ``` -------------------------------- ### Custom Name Handler Function Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Pass a function to the `names` parameter to dynamically handle variable lookups. This allows for complex logic in retrieving variable values. ```pycon >>> def name_handler(node): return ord(node.id[0].lower(a))-96 >>> simple_eval('a + b', names=name_handler) 3 ``` -------------------------------- ### Evaluate List Comprehensions with EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Supports list comprehensions for creating lists based on existing iterables, including filtering and transformations. Requires an iterable to be present in the expression or available via names. ```python # List comprehensions result = s.eval("[x * 2 for x in [1, 2, 3, 4, 5]]") # Output: [2, 4, 6, 8, 10] result = s.eval("[x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 == 0]") # Output: [2, 4, 6, 8, 10] ``` -------------------------------- ### Viewing and Modifying MAX_STRING_LENGTH Limit Source: https://context7.com/danthedeckie/simpleeval/llms.txt Check the default MAX_STRING_LENGTH and adjust it to control the maximum size of string or iterable results. Shows exceeding the modified limit. ```python # String/iterable length limits print(f"Default MAX_STRING_LENGTH: {simpleeval.MAX_STRING_LENGTH}") # 100000 simpleeval.MAX_STRING_LENGTH = 1000 try: simple_eval("'x' * 2000") except simpleeval.IterableTooLong: print("String too long") # Output: String too long simpleeval.MAX_STRING_LENGTH = 100000 # Reset ``` -------------------------------- ### Evaluate Complex Expression Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Handles complex and nested arithmetic expressions including addition, division, modulo, and exponentiation. ```python simple_eval("21 + 19 / 7 + (8 % 3) ** 9") ``` -------------------------------- ### Handling FunctionNotDefined Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch FunctionNotDefined when an undefined function is called. The exception provides the function name and the expression. ```python from simpleeval import ( simple_eval, SimpleEval, InvalidExpression, FunctionNotDefined, NameNotDefined, FeatureNotAvailable, NumberTooHigh, IterableTooLong, AttributeDoesNotExist, ) # FunctionNotDefined - calling undefined function try: simple_eval("undefined_func(42)") except FunctionNotDefined as e: print(f"Function error: {e.func_name} in '{e.expression}'") # Output: Function error: undefined_func in 'undefined_func(42)' ``` -------------------------------- ### Evaluate Conditional Expressions Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Evaluate Python-style 'if x then y else z' expressions. This can be used for simple conditional logic within evaluated strings. ```pycon >>> simple_eval("'equal' if x == y else 'not equal'", ... names={"x": 1, "y": 2}) 'not equal' ``` ```pycon >>> simple_eval("'a' if 1 == 2 else 'b' if 2 == 3 else 'c'") 'c' ``` -------------------------------- ### Evaluate Expression with Custom Function Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Extend functionality by providing custom functions to simple_eval. The functions argument accepts a dictionary mapping function names to callable objects. ```python simple_eval("square(11)", functions={"square": lambda x: x*x}) ``` -------------------------------- ### Handling NameNotDefined Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch NameNotDefined when an undefined variable is used. The exception includes the variable name and the expression. ```python # NameNotDefined - using undefined variable try: simple_eval("x + y") except NameNotDefined as e: print(f"Name error: '{e.name}' in expression '{e.expression}'") # Output: Name error: 'x' in expression 'x + y' ``` -------------------------------- ### Nested Comprehensions with External Names in EvalWithCompoundTypes Source: https://context7.com/danthedeckie/simpleeval/llms.txt Combine comprehensions with external variables defined in `s.names`. This allows complex data transformations based on provided context. ```python # Nested comprehensions with external names s.names = {"data": [1, 2, 3, 4, 5]} result = s.eval("[x + 10 for x in data if x > 2]") # Output: [13, 14, 15] ``` -------------------------------- ### Restrict Module Attributes with allowed_attrs Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Further restrict access to module attributes by passing an `allowed_attrs` set to `ModuleWrapper`. This ensures only specified attributes are accessible. ```python >>> s = SimpleEval(names={ ... 'path': ModuleWrapper(os.path, allowed_attrs={'exists', 'join'}) ... }) >>> s.eval("path.exists('/etc/passwd')") ``` ```python >>> s.eval("path.dirname('/etc/passwd')") # Not in allowed_attrs ``` -------------------------------- ### Handling NumberTooHigh Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch NumberTooHigh when a computation result is excessively large, preventing potential denial-of-service attacks. ```python # NumberTooHigh - computation would take too long try: simple_eval("9 ** 9 ** 9") except NumberTooHigh as e: print(f"Number too high: {e}") # Output: Number too high: Sorry! I don't want to evaluate 9 ** 387420489 ``` -------------------------------- ### Modify SimpleEval Instance After Creation Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Update the `names` attribute of an existing `SimpleEval` instance to change available variables. This allows for dynamic modification of the evaluation context. ```python s.names['fortytwo'] = 42 ``` -------------------------------- ### Handling InvalidExpression Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch InvalidExpression for empty or malformed expressions that cannot be parsed or evaluated. ```python # InvalidExpression - empty or malformed expression try: simple_eval("") except InvalidExpression as e: print(f"Invalid: {e}") # Output: Invalid: Sorry, cannot evaluate empty string ``` -------------------------------- ### Handling AttributeDoesNotExist Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch AttributeDoesNotExist when accessing a non-existent attribute on an object within the evaluated expression. ```python # AttributeDoesNotExist s = SimpleEval(names={"obj": {"a": 1}}) try: s.eval("obj.nonexistent") except AttributeDoesNotExist as e: print(f"Attribute error: '{e.attr}'") # Output: Attribute error: 'nonexistent' ``` -------------------------------- ### Handling IterableTooLong Exception Source: https://context7.com/danthedeckie/simpleeval/llms.txt Catch IterableTooLong when an operation would result in an excessively long string or iterable, safeguarding resources. ```python # IterableTooLong - result would be too large try: simple_eval("'x' * 500000") except IterableTooLong as e: print(f"Too long: {e}") # Output: Too long: Sorry, I will not evaluate something that long. ``` -------------------------------- ### Define Function to Modify Names Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Assign a custom function to `s.functions` that can modify the `s.names` dictionary. This enables 'script-like' behavior within evaluations. ```python s = SimpleEval() def set_val(name, value): s.names[name.value] = value.value return value.value s.functions = {'set': set_val} s.eval("set('age', 111)") ``` -------------------------------- ### Create Custom Evaluator to Disallow Method Calls Source: https://github.com/danthedeckie/simpleeval/blob/main/README.rst Extend `SimpleEval` to create a custom evaluator that prevents method invocations. This is achieved by overriding the `_eval_call` method and raising `FeatureNotAvailable` for attribute calls. ```python import ast import simpleeval class EvalNoMethods(simpleeval.SimpleEval): def _eval_call(self, node): if isinstance(node.func, ast.Attribute): raise simpleeval.FeatureNotAvailable("No methods please, we're British") ``` -------------------------------- ### Evaluator with Variable Assignment Source: https://context7.com/danthedeckie/simpleeval/llms.txt Extend the evaluator to allow setting variables during expression evaluation. This is useful for dynamic expression processing. ```python class EvalWithAssignment(EvalWithCompoundTypes): """Evaluator that allows setting variables during evaluation""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.functions["set"] = self._set_variable def _set_variable(self, name, value): self.names[name] = value return value s = EvalWithAssignment() s.eval("set('x', 10)") s.eval("set('y', 20)") result = s.eval("x + y") # Output: 30 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.