### Complete Asteval Configuration Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md A comprehensive example demonstrating the initialization of an Asteval Interpreter with multiple configuration options, including output redirection and custom symbols. ```python from asteval import Interpreter import io # Example configuration (details omitted as per prompt) # interp = Interpreter(...) ``` -------------------------------- ### Install Asteval from Source Source: https://github.com/lmfit/asteval/blob/master/doc/installation.md Install Asteval after cloning the repository or downloading the source code. This command installs the package from the local source tree. ```bash pip install . ``` -------------------------------- ### Full Asteval Usage Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/START_HERE.md Demonstrates the complete workflow of using Asteval, from import and configuration to evaluation, function definition, error handling, and result access. ```python # 1. Import (see README.md) from asteval import Interpreter # 2. Create with configuration (see configuration.md) interp = Interpreter( use_numpy=True, readonly_symbols=['pi'], user_symbols={'pi': 3.14159} ) # 3. Evaluate expressions (see api-reference/interpreter.md) interp.eval('x = 10') result = interp.eval('x + 5') # 15 # 4. Define functions (see api-reference/procedure.md) interp.eval('def square(n): return n**2') result = interp.eval('square(4)') # 16 # 5. Handle errors (see errors.md) try: interp.eval('bad_variable', raise_errors=True) except NameError as e: print(f"Error: {e}") # 6. Access results (see api-reference/interpreter.md) print(interp.symtable['result']) print(interp.user_defined_symbols()) ``` -------------------------------- ### Install Latest Stable Asteval with pip Source: https://github.com/lmfit/asteval/blob/master/doc/installation.md Use this command to install the latest stable version of Asteval from PyPI. This is the recommended method for most users. ```bash pip install asteval ``` -------------------------------- ### Interpreter Configuration Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Demonstrates how to create an Interpreter instance with a custom configuration dictionary to disable specific features like loops. Shows how to verify the applied configuration. ```python from asteval import Interpreter # Create interpreter with custom config config = {'for': False, 'while': False} # Disable loops interp = Interpreter(config=config) # Verify configuration print(interp.config['for']) # False ``` -------------------------------- ### Interpreter Constructor Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Demonstrates initializing the Interpreter with various configuration options, including disabling specific node types and enabling others via keyword arguments. ```python interp = Interpreter(no_import=True, with_if=True) ``` -------------------------------- ### Get Operator Function using op2func Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Demonstrates how to use the `op2func` utility to get the Python function associated with an AST operator. The example shows retrieving the function for addition and then using it. ```python from asteval.astutils import op2func import ast # Get operator function add_func = op2func(ast.Add()) result = add_func(5, 3) print(result) # 8 # Safe pow prevents DOS pow_func = op2func(ast.Pow()) # pow_func(2, 20000) would raise RuntimeError (exponent too large) ``` -------------------------------- ### Create and Use Nested Groups Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/astutils.md Demonstrates how to create a group with nested search groups and access symbols through direct access and the 'get' method. ```python from asteval import Group math_group = Group(name='math', sin=lambda x: x, cos=lambda x: x) main_group = Group(name='main', searchgroups=['math']) main_group['math'] = math_group # Access directly print(main_group['sin']) # None (not in main) # Search via get print(main_group.get('sin')) # function (found in math) # Attribute access main_group.x = 10 print(main_group.x) # 10 ``` -------------------------------- ### Symbol Table Creation and Usage Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Shows how to obtain the default symbol table using `make_symbol_table` and how to create an Interpreter with custom user-defined symbols. Verifies the presence of built-in and custom symbols. ```python from asteval import Interpreter from asteval.astutils import make_symbol_table # Get default symbol table symtable = make_symbol_table() print('sin' in symtable) # True print('sqrt' in symtable) # True # Create interpreter with custom symbols custom_syms = {'my_var': 10, 'my_func': lambda x: x**2} interp = Interpreter(user_symbols=custom_syms) print(interp.symtable['my_var']) # 10 ``` -------------------------------- ### Example AST Node Handler Pattern Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Illustrates the general structure of an AST node handler method, including recursive evaluation of child nodes and operator application. ```python def on_binop(self, node): """Binary operation: a + b, a * b, etc.""" left_val = self.run(node.left) # Evaluate left operand right_val = self.run(node.right) # Evaluate right operand op_func = op2func(node.op) # Get operator function return op_func(left_val, right_val) # Apply operator ``` -------------------------------- ### Minimal Configuration Interpreter Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Create an Interpreter with a minimal configuration, disabling many node types for a restricted evaluator. This example demonstrates basic math operations and how control flow and function definitions are disabled. ```python from asteval import Interpreter minimal_interp = Interpreter(minimal=True) # Basic math works result = minimal_interp.eval('2 + 3 * 4') print(result) # 8 # Control flow disabled try: minimal_interp.eval('if True: x = 1') except NotImplementedError: print("If statements disabled in minimal mode") # Function definitions disabled try: minimal_interp.eval('def f(): return 1') except NotImplementedError: print("Function definitions disabled") ``` -------------------------------- ### Nested Symbol Table Usage Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Demonstrates using an Interpreter with `nested_symtable=True` to access symbols through namespaces like 'math'. Shows how to evaluate expressions using both namespaced and direct symbol access. ```python from asteval import Interpreter # Nested symbol table interp = Interpreter(nested_symtable=True) # Access math functions via namespace result = interp.eval('math.sin(0)') print(result) # 0.0 # Or directly (due to searchgroups) result = interp.eval('sin(0)') print(result) # 0.0 # Access structure programmatically symtable = interp.symtable print(symtable['__name__']) # '_main' print('math' in symtable) # True ``` -------------------------------- ### NumPy Functions Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md Details the availability of NumPy functions within Asteval, including common categories and examples, provided NumPy is installed. ```APIDOC ## NumPy Functions (if installed) 100+ NumPy functions available, including: | Category | Examples | |----------|----------| | Array creation | array, arange, linspace, zeros, ones, eye | | Array manipulation | reshape, transpose, flatten, concatenate | | Math functions | sin, cos, sqrt, log, exp, abs | | Statistics | mean, std, var, median, percentile | | Linear algebra | dot, cross, transpose (also linalg submodule) | | Searching | argmax, argmin, where, searchsorted | | Sorting | sort, argsort | | Logic | any, all, logical_and, logical_or | Plus aliases: ln (→ log), asin (→ arcsin), acos (→ arccos), atan (→ arctan) ``` -------------------------------- ### Getting Function Signature with __signature__ Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Illustrates how to obtain the string representation of a function's signature using the __signature__ method for functions with different argument types: simple, with defaults, with varargs, and a complex combination. ```python from asteval import Interpreter interp = Interpreter() # Simple function interp.eval('def simple(a, b): return a + b') sig = interp.symtable['simple'].__signature__() print(sig) # 'simple(a, b)' # With defaults interp.eval('def with_defaults(a, b=10): return a + b') sig = interp.symtable['with_defaults'].__signature__() print(sig) # 'with_defaults(a, b=10)' # With varargs interp.eval('def varargs(a, *args): return sum([a] + list(args))') sig = interp.symtable['varargs'].__signature__() print(sig) # 'varargs(a, *args)' # Complex signature interp.eval('def complex_sig(a, b=1, *args, **kwargs): pass') sig = interp.symtable['complex_sig'].__signature__() print(sig) # 'complex_sig(a, b=1, *args, **kwargs)' ``` -------------------------------- ### ExceptionHolder Usage Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Illustrates how to capture and inspect errors using `raise_errors=False` and checking the `interp.error` list. Shows how to retrieve the exception name and formatted message from an ExceptionHolder object. ```python from asteval import Interpreter interp = Interpreter() # Cause an error without raising interp.eval('undefined_variable + 1', raise_errors=False) # Check error list if interp.error: err = interp.error[0] exc_name, msg = err.get_error() print(f"Error: {exc_name}") print(f"Message: {msg}") ``` -------------------------------- ### Evaluate Slice Objects Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates the evaluation of slice notation (e.g., `start:stop:step`) which results in a Python slice object. ```python interp.eval('a[1:5:2]') # Evaluates using slice(1, 5, 2) interp.eval('a[::2]') # Evaluates using slice(None, None, 2) ``` -------------------------------- ### Get Function Signature Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/astutils.md Demonstrates how to retrieve the signature string of a function defined within the Asteval interpreter. ```python from asteval import Interpreter interp = Interpreter() interp.eval('def multiply(a, b=1, *args, **kwargs): return a * b') func = interp.symtable['multiply'] print(func.__signature__()) # Output: 'multiply(a, b=1, *args, **kwargs)' ``` -------------------------------- ### Procedure Local Scope Example Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Demonstrates that each procedure call creates its own local symbol table, isolating variables. ```python from asteval import Interpreter interp = Interpreter() interp.eval(''' def scope_test(): local_var = "I am local" return local_var scope_test() ''') # local_var doesn't exist in global scope print('local_var' in interp.symtable) # False # But can access return value print(interp.eval('scope_test()')) # 'I am local' ``` -------------------------------- ### NUMPY_TABLE Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md A dictionary containing NumPy functions, available if NumPy is installed. ```APIDOC ## NUMPY_TABLE ### Description A dictionary containing NumPy functions, available if NumPy is installed. ### Type dict ``` -------------------------------- ### Create Interpreter with Config Dict Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Instantiate an Interpreter using a configuration dictionary to define enabled/disabled features. ```python from asteval import Interpreter config = { 'import': False, 'importfrom': False, 'for': True, 'while': True, 'if': True, } interp = Interpreter(config=config) ``` -------------------------------- ### NUMPY_TABLE Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/astutils.md A dictionary containing NumPy functions, available if NumPy is installed. ```APIDOC ## NUMPY_TABLE ### Description A dictionary containing NumPy functions, available if NumPy is installed. ### Value ```python dict ``` ``` -------------------------------- ### HAS_NUMPY Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md A boolean indicating whether the NumPy library is installed and available for use. ```APIDOC ## HAS_NUMPY ### Description A boolean indicating whether the NumPy library is installed and available for use. ### Type bool ``` -------------------------------- ### Create an Asteval Interpreter Source: https://github.com/lmfit/asteval/blob/master/doc/basics.md Import the Interpreter class and create an instance to begin using Asteval. ```pycon >>> from asteval import Interpreter >>> aeval = Interpreter() ``` -------------------------------- ### NumPy Functions Dictionary Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/astutils.md Represents the dictionary of NumPy functions available in Asteval, if NumPy is installed. ```python NUMPY_TABLE: dict ``` -------------------------------- ### Initialize Interpreter in Restricted Mode Source: https://github.com/lmfit/asteval/blob/master/_autodocs/START_HERE.md Illustrates how to initialize the Interpreter with restricted mode enabled for enhanced safety. ```python interp = Interpreter(minimal=True) # Restricted mode ``` -------------------------------- ### Get Function Docstring Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Retrieves the docstring of a defined function. Returns None if no docstring is present. ```python from asteval import Interpreter interp = Interpreter() # With docstring interp.eval(''' def documented(x): """Multiply x by 2.""" return x * 2 ''') func = interp.symtable['documented'] print(func.__getdoc__()) # 'Multiply x by 2.' # Without docstring interp.eval('def undocumented(x): return x * 2') func = interp.symtable['undocumented'] print(func.__getdoc__()) # None ``` -------------------------------- ### Initialize Interpreter with Comprehensive Configuration Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Configure interpreter nodes, symbol table behavior, output writers, and limits during initialization. This sets up a fully featured interpreter with custom symbols and numpy support. ```python from asteval import Interpreter import io output = io.StringIO() errors = io.StringIO() interp = Interpreter( # Node type configuration minimal=False, with_import=False, with_for=True, with_while=True, with_try=True, with_functiondef=True, with_lambda=True, # Symbol table nested_symtable=True, use_numpy=True, readonly_symbols=['pi', 'e'], builtins_readonly=False, user_symbols={ 'version': '1.0', 'author': 'Jane Doe', }, # Output writer=output, err_writer=errors, # Limits max_statement_length=100000, ) # Use the configured interpreter code = ''' def greet(name): return f"Hello, {name}!" result = greet("World") pi_value = pi for i in range(3): print(f"Iteration {i}") ''' interp.eval(code) print("Output:", output.getvalue()) print("Result:", interp.symtable['result']) print("Pi:", interp.symtable['pi_value']) ``` -------------------------------- ### Create Interpreter with Keyword Arguments Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Instantiate an Interpreter using keyword arguments to enable or disable specific node types. ```python # Using with_ and no_ interp = Interpreter( with_for=True, with_while=True, no_import=True ) ``` -------------------------------- ### Basic Interpreter Usage Source: https://github.com/lmfit/asteval/blob/master/_autodocs/README.md Demonstrates creating an interpreter, evaluating simple expressions, defining and using variables, and defining and calling functions. ```python from asteval import Interpreter # Create an interpreter interp = Interpreter() # Evaluate expressions result = interp.eval('2 + 3 * 4') print(result) # 14 # Define and use variables interp.eval('x = 10') interp.eval('y = 20') result = interp.eval('x + y') print(result) # 30 # Define functions interp.eval('\ def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) ') result = interp.eval('fibonacci(10)') print(result) # 55 ``` -------------------------------- ### Minimal Interpreter Configuration Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Creates a minimal interpreter with basic math operations. Demonstrates that for loops are disabled in minimal mode. ```python # Create a minimal interpreter with only basic math operations interp = Interpreter(minimal=True) result = interp.eval('2 + 2 * 3') # Works print(result) # Output: 8 # For loops are disabled in minimal mode try: interp.eval('for i in range(3): x = i') except NotImplementedError: print("For-loops not supported in minimal mode") ``` -------------------------------- ### Managing Variables and Symbol Table Source: https://github.com/lmfit/asteval/blob/master/_autodocs/INDEX.md Demonstrates how to add initial variables, access the symbol table, modify variables directly, and retrieve user-defined symbols. ```python from asteval import Interpreter interp = Interpreter() # Add initial values interp.eval('x = 5') interp.eval('y = 10') # Access symbol table print(interp.symtable['x']) # 5 print(interp.symtable['y']) # 10 # Modify via symbol table interp.symtable['x'] = 100 # Verify in evaluations result = interp.eval('x + y') print(result) # 110 # Get user-defined symbols user_syms = interp.user_defined_symbols() print(user_syms) # {'x', 'y'} ``` -------------------------------- ### Initialize and Evaluate Simple Expression Source: https://github.com/lmfit/asteval/blob/master/_autodocs/START_HERE.md Demonstrates the basic usage of the Interpreter class to evaluate a simple arithmetic expression. ```python from asteval import Interpreter interp = Interpreter() result = interp.eval('2 + 2') ``` -------------------------------- ### Call Procedure with Keyword Arguments and Defaults Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Shows how to call a procedure using default values for arguments and explicit keyword arguments. ```python from asteval import Interpreter interp = Interpreter() interp.eval(''' def power(base, exponent=2): return base ** exponent ''') result1 = interp.eval('power(2)') # Uses default exponent=2 result2 = interp.eval('power(2, 3)') # Explicit exponent=3 result3 = interp.eval('power(base=2, exponent=10)') # Keyword args print(result1) print(result2) print(result3) ``` -------------------------------- ### Clone Asteval Development Version from GitHub Source: https://github.com/lmfit/asteval/blob/master/doc/installation.md Clone the Asteval repository from GitHub to get the latest development version. This is useful for developers or users who need the most recent features. ```bash git clone https://github.com/lmfit/asteval.git ``` -------------------------------- ### Using Asteval's Nested Symbol Table Source: https://github.com/lmfit/asteval/blob/master/doc/api.md Demonstrates the initialization and basic usage of Asteval's nested symbol table, allowing attribute-style access to symbols. ```python >>> from asteval import Interpreter >>> aeval = Interpreter(nested_symtable=True) >>> aeval('x = 3') >>> aeval.symtable['x'] # as with default dictionary 3 >>> aeval.symtable.x # new 3 >>> aeval.symtable.y = 7 # new >>> aeval('print(x+y)') 10 ``` -------------------------------- ### Construct Collections (List, Tuple, Dict, Set) Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates the evaluation of collection constructors for lists, tuples, dictionaries, and sets. ```python interp.eval('[1, 2, 3]') # [1, 2, 3] interp.eval('(1, 2, 3)') # (1, 2, 3) interp.eval('{"a": 1, "b": 2}') # {'a': 1, 'b': 2} interp.eval('{1, 2, 3}') # {1, 2, 3} ``` -------------------------------- ### Calling a Procedure via __call__ Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Demonstrates how to define a function in asteval, retrieve its Procedure object, and then call it directly using the __call__ method with positional and keyword arguments. ```python from asteval import Interpreter interp = Interpreter() # Define a function interp.eval('\ def add(a, b):\ return a + b ') # Get the Procedure object add_proc = interp.symtable['add'] # Call it via __call__ result = add_proc(3, 4) print(result) # 7 # Also works via eval result = interp.eval('add(10, 20)') print(result) # 30 # With keyword arguments result = add_proc(b=5, a=10) print(result) # 15 ``` -------------------------------- ### Get User-Defined Symbols Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Retrieve a set of symbols that were explicitly added to the interpreter's symbol table. This method helps identify custom variables and functions defined during runtime, excluding built-ins. ```python interp = Interpreter() interp.eval('x = 1') interp.eval('y = 2') interp.eval('z = 3') user_syms = interp.user_defined_symbols() print(user_syms) ``` -------------------------------- ### Capturing All Interpreter Output Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Sets up the interpreter to capture all its standard output into a StringIO object. This is useful for testing or logging interpreter results. ```python from asteval import Interpreter import io import sys # Capture all interpreter output output = io.StringIO() interp = Interpreter(writer=output) interp.eval(''' for i in range(3): print(f"Count: {i}") ''') print("Captured output:") print(output.getvalue()) ``` -------------------------------- ### Preventing Resource Hogging with Large Arrays Source: https://github.com/lmfit/asteval/blob/master/doc/motivation.md Demonstrates a potentially resource-intensive calculation using numpy.arange and numpy.sqrt. This example highlights the need for runtime checks to prevent excessive CPU time and memory usage. ```python from asteval import Interpreter aeval = Interpreter() txt = """ nmax = 1e8 a = sqrt(arange(nmax)) # using numpy.sqrt() and numpy.arange() """ aeval.eval(txt) ``` -------------------------------- ### Creating and Using a Custom Symbol Table Source: https://github.com/lmfit/asteval/blob/master/doc/api.md Shows how to create a custom symbol table with user-defined functions and numpy integration using `make_symbol_table`. ```python from asteval import Interpreter, make_symbol_table import numpy as np def cosd(x): "cos with angle in degrees" return np.cos(np.radians(x)) def sind(x): "sin with angle in degrees" return np.sin(np.radians(x)) def tand(x): "tan with angle in degrees" return np.tan(np.radians(x)) syms = make_symbol_table(use_numpy=True, cosd=cosd, sind=sind, tand=tand) aeval = Interpreter(symtable=syms) print(aeval("sind(30)")) ``` -------------------------------- ### Accessing Asteval Safety Limits and Configuration Source: https://github.com/lmfit/asteval/blob/master/_autodocs/errors.md Demonstrates how to access predefined safety limits like MAX_EXPONENT, MAX_STR_LEN, and MAX_SHIFT from `asteval.astutils`. It also shows how to dynamically adjust limits like `max_statement_length` on an Interpreter instance. ```python from asteval.astutils import MAX_EXPONENT, MAX_STR_LEN, MAX_SHIFT from asteval import Interpreter interp = Interpreter() print(f"Max exponent: {MAX_EXPONENT}") # 10000 print(f"Max string length: {MAX_STR_LEN}") # 262144 print(f"Max shift: {MAX_SHIFT}") # 1000 # Increase max statement length interp.max_statement_length = 1000000 ``` -------------------------------- ### Manipulate Symbol Table Source: https://github.com/lmfit/asteval/blob/master/doc/api.md Access and modify the Interpreter's symbol table to define or change variables and functions available for expression evaluation. This example shows how to set a variable 'x' and then use it in an expression. ```default >>> from asteval import Interpreter >>> aeval = Interpreter() >>> aeval.symtable['x'] = 10 >>> aeval('sqrt(x)') 3.1622776601683795 ``` -------------------------------- ### Custom Symbol Table Initialization Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Adds custom functions and variables to the interpreter at initialization. Shows how to define and use a custom function. ```python # Add custom functions and variables at initialization def my_func(x): return x ** 2 interp = Interpreter(user_symbols={'my_func': my_func, 'pi': 3.14159}) result = interp.eval('my_func(5)') print(result) # Output: 25 ``` -------------------------------- ### Enabling or Disabling NumPy Integration Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Shows how to control whether the interpreter uses NumPy. When enabled (default if installed), array-related functions are available. Disabling it prevents NumPy usage and raises errors for related functions. ```python from asteval import Interpreter # With NumPy (default if installed) interp_with_np = Interpreter(use_numpy=True) result = interp_with_np.eval('array([1, 2, 3])') print(type(result)) # # Without NumPy interp_no_np = Interpreter(use_numpy=False) try: result = interp_no_np.eval('array([1, 2, 3])', raise_errors=True) except NameError as e: print(f"NumPy not available: {e}") ``` -------------------------------- ### Create Minimal Interpreter Source: https://github.com/lmfit/asteval/blob/master/doc/api.md Instantiate an Interpreter with `minimal=True` to disable all optional Python AST nodes listed in the documentation, resulting in a bare-bones mathematical language. ```python >>> from asteval import Interpreter >>> >>> aeval_min = Interpreter(minimal=True) >>> aeval_min.config {'import': False, 'importfrom': False, 'assert': False, 'augassign': False, 'delete': False, 'if': False, 'ifexp': False, 'for': False, 'formattedvalue': False, 'functiondef': False, 'print': False, 'raise': False, 'lambda': False, 'listcomp': False, 'dictcomp': False, 'setcomp': False, 'try': False, 'while': False, 'with': False, 'nested_symtable': False} ``` -------------------------------- ### __version__ Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md The version string of the asteval library. ```APIDOC ## __version__ ### Description The version string of the asteval library. ### Type str ``` -------------------------------- ### Accessing Math Functions Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Demonstrates accessing built-in math functions within the Asteval interpreter's 'math' namespace. ```python from asteval import Interpreter interp = Interpreter() result = interp.eval('math.sin(0)') print(result) # 0.0 ``` -------------------------------- ### Python: Lambda Expressions in Asteval Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Demonstrates the creation and usage of lambda expressions within Asteval, which result in Procedure objects with `is_lambda=True`. It shows how to define and call lambdas, and access their properties. ```python from asteval import Interpreter interp = Interpreter() # Define lambda via eval interp.eval('square = lambda x: x ** 2') # Call it result = interp.eval('square(5)') print(result) # 25 # Get the Procedure lambda_proc = interp.symtable['square'] print(lambda_proc.name) # 'lambda' print(lambda_proc.__argnames__) # ['x'] ``` -------------------------------- ### Parse and Run Code with Interpreter Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Demonstrates parsing a Python statement into an AST node and then executing it using the run method, updating the interpreter's symbol table. ```python interp = Interpreter() node = interp.parse('x = 2 + 3') result = interp.run(node) print(result) # x is now in the symbol table print(interp.symtable['x']) # Output: 5 ``` -------------------------------- ### Import asteval.astutils Module Exports Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md Import all utility functions and classes from the asteval.astutils module. ```python from asteval.astutils import ( NameFinder, ExceptionHolder, Empty, Group, Procedure, ReturnedNone, valid_symbol_name, valid_varname, get_ast_names, make_symbol_table, op2func, safe_format, safe_getattr, safe_pow, safe_mult, safe_add, safe_lshift, SafeFormatter, HAS_NUMPY, HAS_NUMPY_FINANCIAL, ) ``` -------------------------------- ### Evaluate F-string Components Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Shows how to evaluate f-string components, including formatted values within strings. ```python interp.eval('x = 5') interp.eval('f"Value: {x}"') # 'Value: 5' ``` -------------------------------- ### AST Inspection and Evaluation Source: https://github.com/lmfit/asteval/blob/master/_autodocs/INDEX.md Demonstrates parsing an expression into an AST node without immediate evaluation, inspecting the AST for names, and then running the AST. ```python from asteval import Interpreter from asteval.astutils import get_ast_names interp = Interpreter() # Parse code without evaluating ast_node = interp.parse('result = a + b + c') # Find all names used names = get_ast_names(ast_node) print(names) # ['a', 'b', 'c', 'result'] # Now run it interp.eval('a = 1') interp.eval('b = 2') interp.eval('c = 3') interp.run(ast_node) print(interp.symtable['result']) # 6 ``` -------------------------------- ### Python: Recursive Procedure in Asteval Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Illustrates the support for recursion in Asteval procedures, demonstrating a factorial function. Asteval handles recursion with reasonable limits to prevent stack overflows. ```python from asteval import Interpreter interp = Interpreter() interp.eval('\ def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) result = factorial(5) ') print(interp.symtable['result']) # 120 ``` -------------------------------- ### run Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Executes a parsed Abstract Syntax Tree (AST) node representation. This method is fundamental for evaluating code that has already been parsed. ```APIDOC ## run ### Description Execute a parsed AST node representation. ### Method run ### Parameters #### Path Parameters - **node** (ast.Node or str or None) - Required - Parsed AST node, Python code string, or None. - **expr** (str) - Optional - Source expression text for error reporting. - **lineno** (int) - Optional - Line number for error reporting. - **with_raise** (bool) - Optional - Whether to raise exceptions on errors. Default: True ### Returns Result of executing the node, or None on error. ### Raises Exceptions if with_raise=True and an error occurs. ### Example ```python interp = Interpreter() ast_node = interp.parse('result = sum([1, 2, 3])') interp.run(ast_node) print(interp.symtable['result']) # Output: 6 ``` ``` -------------------------------- ### Equivalent Expressions with Nested Symbol Table Source: https://github.com/lmfit/asteval/blob/master/doc/api.md Illustrates how expressions using functions and constants from subgroups (like 'math') are equivalent to directly accessing them. ```python >>> aeval('a = b * cos( pi /3)') >>> aeval('a = b * math.cos(math.pi /3)') ``` -------------------------------- ### Execute Parsed AST Node Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Use the `run` method to execute a pre-parsed Abstract Syntax Tree (AST) node. This is useful when you have already parsed an expression and want to evaluate it. Ensure the interpreter is initialized. ```python interp = Interpreter() ast_node = interp.parse('result = sum([1, 2, 3])') interp.run(ast_node) print(interp.symtable['result']) ``` -------------------------------- ### Call Procedure with Variable Keyword Arguments (**kwargs) Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Shows how to capture a variable number of keyword arguments using **kwargs. ```python from asteval import Interpreter interp = Interpreter() interp.eval(''' def build_dict(**kwargs): return kwargs ''') result = interp.eval('build_dict(a=1, b=2, c=3)') print(result) ``` -------------------------------- ### Configure Interpreter for Safety Source: https://github.com/lmfit/asteval/blob/master/_autodocs/START_HERE.md Create an Interpreter instance with minimal features and read-only symbols for enhanced safety. ```python interp = Interpreter(minimal=True, readonly_symbols=['x']) ``` -------------------------------- ### Evaluate Literal Constants Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates how to evaluate different types of literal constants like numbers, strings, None, and booleans using the interpreter. ```python interp.eval('42') # Returns 42 interp.eval('"hello"') # Returns 'hello' interp.eval('None') # Returns None interp.eval('True') # Returns True ``` -------------------------------- ### Call Procedure with Variable Positional Arguments (*args) Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Demonstrates passing a variable number of positional arguments to a procedure using *args. ```python from asteval import Interpreter interp = Interpreter() interp.eval(''' def sum_all(*args): total = 0 for val in args: total = total + val return total ''') result1 = interp.eval('sum_all(1, 2, 3)') result2 = interp.eval('sum_all(10, 20, 30, 40)') print(result1) print(result2) ``` -------------------------------- ### Call Procedure with Positional Arguments Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/procedure.md Demonstrates calling a procedure using only positional arguments. ```python from asteval import Interpreter interp = Interpreter() interp.eval(''' def multiply(a, b): return a * b ''') result = interp.eval('multiply(3, 4)') print(result) ``` -------------------------------- ### Interpreter Constructor Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/interpreter.md Initializes an Interpreter instance with a customizable symbol table, configuration options, and safety features. ```APIDOC ## Interpreter Constructor ### Description Initializes an Interpreter instance with a customizable symbol table, configuration options, and safety features. ### Parameters - **symtable** (dict or Group) - Optional - Dictionary or nested SymbolTable for variable storage. If None, a default symbol table is created. - **nested_symtable** (bool) - Optional - Whether to use a nested symbol table (new-style Group-based) instead of plain dict. Defaults to False. - **user_symbols** (dict) - Optional - Dictionary of user-defined symbols to add to the symbol table at initialization. - **writer** (file-like) - Optional - File-like object for standard output. Defaults to sys.stdout. - **err_writer** (file-like) - Optional - File-like object for standard error. Defaults to sys.stderr. - **use_numpy** (bool) - Optional - Whether to include NumPy functions in the symbol table (if NumPy is installed). Defaults to True. - **max_statement_length** (int) - Optional - Maximum allowed length of expressions in characters. Valid range: 1 to 100,000,000. Defaults to 50000. - **minimal** (bool) - Optional - If True, creates a minimal interpreter with many AST node types disabled. Defaults to False. - **readonly_symbols** (iterable) - Optional - Iterable of symbol names that users cannot assign to. - **builtins_readonly** (bool) - Optional - If True, all built-in symbols present at initialization are marked as read-only. Defaults to False. - **config** (dict) - Optional - Dictionary of node type configurations (True to enable, False to disable). Overrides defaults. - **kws** (dict) - Optional - Additional keyword arguments. Supports legacy 'usersyms' parameter and node config flags (no_ or with_). ### Configuration Flags via Keyword Arguments The constructor accepts keyword arguments in two forms for backward compatibility: - `no_=True` - disables that node type - `with_=True` - enables that node type Example: `Interpreter(no_import=True, with_if=True)` disables imports but enables if-statements. ``` -------------------------------- ### Enabling Imports in Asteval Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Demonstrates how to enable the import functionality within the Asteval interpreter, allowing standard library modules to be imported. Imports are disabled by default for security. ```python from asteval import Interpreter # Enable imports interp = Interpreter(with_import=True) # Or via config interp = Interpreter(config={'import': True, 'importfrom': True}) # Now you can import interp.eval('import json') print('json' in interp.symtable) # True ``` -------------------------------- ### Interpreter Class Initialization Source: https://github.com/lmfit/asteval/blob/master/doc/api.md This section describes the initialization of the Asteval Interpreter class, outlining its various parameters for customization. ```APIDOC ## class asteval.Interpreter ### Description Creates an Asteval Interpreter: a restricted, simplified interpreter of mathematical expressions using Python syntax. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symtable** (dict or None) - Optional - Dictionary or SymbolTable to use as symbol table (if None, one will be created). - **nested_symtable** (bool, optional) - Optional - Whether to use a new-style nested symbol table instead of a plain dict [False]. - **user_symbols** (dict or None) - Optional - Dictionary of user-defined symbols to add to symbol table. - **writer** (file-like or None) - Optional - Callable file-like object where standard output will be sent. - **err_writer** (file-like or None) - Optional - Callable file-like object where standard error will be sent. - **use_numpy** (bool) - Optional - Whether to use functions from numpy. - **max_statement_length** (int) - Optional - Maximum length of expression allowed [50,000 characters]. - **readonly_symbols** (iterable or None) - Optional - Symbols that the user can not assign to. - **builtins_readonly** (bool) - Optional - Whether to blacklist all symbols that are in the initial symtable. - **minimal** (bool) - Optional - Create a minimal interpreter: disable many nodes (see Note 1). - **config** (dict) - Optional - Dictionary listing which nodes to support (see note 2). ### Request Example ```json { "symtable": null, "nested_symtable": false, "user_symbols": {}, "writer": null, "err_writer": null, "use_numpy": true, "max_statement_length": 50000, "readonly_symbols": null, "builtins_readonly": false, "minimal": false, "config": null } ``` ### Response #### Success Response (200) - **Interpreter object** - The newly created Interpreter instance. #### Response Example ```json { "message": "Interpreter created successfully" } ``` ### Notes 1. setting minimal=True is equivalent to setting a config with the following nodes disabled: (‘import’, ‘importfrom’, ‘if’, ‘for’, ‘while’, ‘try’, ‘with’, ‘functiondef’, ‘ifexp’, ‘lambda’, ‘listcomp’, ‘dictcomp’, ‘setcomp’, ‘augassign’, ‘assert’, ‘delete’, ‘raise’, ‘print’) 2. by default ‘import’ and ‘importfrom’ are disabled, though they can be enabled. ``` -------------------------------- ### Import Core asteval Components Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md Import essential components directly from the asteval package for general use. ```python from asteval import ( Interpreter, NameFinder, valid_symbol_name, make_symbol_table, get_ast_names, __version__ ) ``` -------------------------------- ### Handle Exceptions in Asteval Source: https://github.com/lmfit/asteval/blob/master/doc/basics.md Implement a REPL loop to continuously evaluate user input, capture and print any exceptions encountered, or display the result if no errors occur. Requires importing Interpreter and using raw_input. ```pycon >>> from asteval import Interpreter >>> aeval = Interpreter() >>> while True: >>> inp_string = raw_input('dsl:> ') >>> result = aeval(inp_string) >>> if len(aeval.error)>0: >>> for err in aeval.error: >>> print(err.get_error()) >>> else: >>> print(result) ``` -------------------------------- ### Interpreter Configuration Source: https://github.com/lmfit/asteval/blob/master/_autodocs/README.md Illustrates configuring an interpreter with custom output, NumPy support, protected symbols, and user-defined symbols. The `writer` argument captures stdout. ```python from asteval import Interpreter import io # Configure output and features output = io.StringIO() interp = Interpreter( writer=output, # Capture stdout use_numpy=True, # Enable NumPy readonly_symbols=['pi', 'e'], # Protect constants user_symbols={'version': '1.0'}, # Add custom symbols minimal=False, # Full feature set ) # Use the interpreter interp.eval('result = 2 * pi') print(interp.symtable['result']) # 6.28... ``` -------------------------------- ### Evaluate Binary Operations Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates the evaluation of various binary operations like addition, exponentiation, division, and list concatenation. ```python interp.eval('2 + 3') # 5 interp.eval('2 ** 10') # 1024 interp.eval('10 / 2') # 5.0 interp.eval('[1] + [2]') # [1, 2] ``` -------------------------------- ### Asteval Evaluation Pipeline Source: https://github.com/lmfit/asteval/blob/master/_autodocs/INDEX.md Illustrates the flow of source code through Asteval's parsing and execution stages, from source string to final result. ```text Source Code String ↓ parse() ← Parses into AST using ast.parse() ↓ ast.Module (with fix_missing_locations) ↓ run() ← Walks AST using node handlers ↓ node_handlers[node_type](node) ← Each node type has a handler ↓ Evaluate recursively through child nodes ↓ Result value ``` -------------------------------- ### Evaluate Comparison Operations Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates the evaluation of comparison operations, including simple comparisons, chained comparisons, and membership testing. ```python interp.eval('5 > 3') # True interp.eval('1 < 2 < 3') # True interp.eval('1 < 2 > 0') # True interp.eval('"a" in "abc"') # True ``` -------------------------------- ### Implement a custom node handler Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/node-handlers.md Demonstrates how to define and set a custom handler for a specific node type (e.g., 'for' loop). The custom handler can override the default behavior. ```python from asteval import Interpreter def my_for_handler(node): """Custom for loop handler.""" print(f"Custom for loop detected: {node}") # Don't actually execute the loop return None interp = Interpreter() interp.set_nodehandler('for', my_for_handler) # Now uses custom handler interp.eval('for i in range(3): x = i') # Prints: Custom for loop detected: ``` -------------------------------- ### Define and Execute User-Defined Functions Source: https://github.com/lmfit/asteval/blob/master/doc/basics.md Define custom functions using a 'def' block and execute them with specified arguments. Ensure the Interpreter is imported. ```default >>> from asteval import Interpreter >>> aeval = Interpreter() >>> code = """ def func(a, b, norm=1.0): return (a + b)/norm """ >>> aeval(code) >>> aeval("func(1, 3, norm=10.0)") 0.4 ``` -------------------------------- ### Procedure Constructor Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md Initializes a Procedure object. Use this to define custom functions or procedures within Asteval. ```python Procedure(name, interp, doc=None, lineno=None, body=None, text=None, args=None, kwargs=None, vararg=None, varkws=None, is_lambda=False) ``` -------------------------------- ### Define and Access Procedure Object Source: https://github.com/lmfit/asteval/blob/master/_autodocs/types.md Demonstrates how to define a function using `interp.eval()` and then access it as a Procedure object from the symbol table to inspect its properties and call it. ```python from asteval import Interpreter interp = Interpreter() # Define a function interp.eval('' def multiply(a, b=1): """Multiply two numbers.""" return a * b '') # Access as Procedure object proc = interp.symtable['multiply'] print(proc.__name__) # 'multiply' print(proc.__argnames__) # ['a'] print(proc.__kwargs__) # [('b', 1)] print(proc.__doc__) # 'Multiply two numbers.' # Call it result = proc(3, 4) print(result) # 12 ``` -------------------------------- ### Interpreter Class Constructor Source: https://github.com/lmfit/asteval/blob/master/_autodocs/EXPORTS.md Instantiate the Interpreter class with various configuration options. ```python Interpreter(symtable=None, nested_symtable=False, user_symbols=None, writer=None, err_writer=None, use_numpy=True, max_statement_length=50000, minimal=False, readonly_symbols=None, builtins_readonly=False, config=None, **kws) ``` -------------------------------- ### Safe String Formatting Source: https://github.com/lmfit/asteval/blob/master/_autodocs/api-reference/astutils.md Demonstrates safe string formatting using asteval's Interpreter to prevent access to unsafe attributes. This is useful when evaluating user-provided format strings. ```python from asteval import Interpreter interp = Interpreter() # In asteval context, format strings are automatically safe result = interp.eval('"x={x}".format(x=5)') print(result) # Output: 'x=5' # This would be blocked in asteval: # result = interp.eval('"x={x.__class__}".format(x=5)') # Raises AttributeError ``` -------------------------------- ### Execute Basic Expressions and Loops Source: https://github.com/lmfit/asteval/blob/master/doc/basics.md Evaluate mathematical expressions and execute multi-line code blocks, including loops, within the Asteval interpreter. ```default >>> aeval('x = sqrt(3)') ``` ```default >>> aeval('print(x)') 1.73205080757 ``` ```default >>> aeval(''' for i in range(10): print(i, sqrt(i), log(1+1)) ''') 0 0.0 0.0 1 1.0 0.69314718056 2 1.41421356237 1.09861228867 3 1.73205080757 1.38629436112 4 2.0 1.60943791243 5 2.2360679775 1.79175946923 6 2.44948974278 1.94591014906 7 2.64575131106 2.07944154168 8 2.82842712475 2.19722457734 9 3.0 2.30258509299 ``` -------------------------------- ### Interpreter with User Symbols Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Initialize an Interpreter with user-defined symbols for constants like pi, e, and the golden ratio. Demonstrates evaluating an expression using one of these user-defined symbols. ```python from asteval import Interpreter # Add user symbols at initialization interp = Interpreter( user_symbols={ 'pi': 3.14159265359, 'e': 2.71828182846, 'golden_ratio': 1.61803398875, } ) result = interp.eval('2 * pi') print(result) # 6.28318530718 ``` -------------------------------- ### Math-Only Configuration Interpreter Source: https://github.com/lmfit/asteval/blob/master/_autodocs/configuration.md Configure an Interpreter for math-only operations by disabling most features and then selectively re-enabling essential ones like 'if' and 'functiondef'. Demonstrates evaluating an expression with exponentiation and a math function. ```python from asteval import Interpreter # Disable most features, keep basic math math_only = Interpreter(minimal=True) # Re-enable essential features if needed math_only.set_nodehandler('if') math_only.set_nodehandler('functiondef') result = math_only.eval('result = 2 ** 10 + sqrt(16)') print(result) # None (assigns to variable) print(math_only.symtable['result']) # 1028.0 ``` -------------------------------- ### Safe User Input Evaluation Source: https://github.com/lmfit/asteval/blob/master/_autodocs/README.md Shows how to create a restricted interpreter using `minimal=True` for safe evaluation of user-provided input. Errors are caught and handled. ```python from asteval import Interpreter # Create a restricted interpreter interp = Interpreter(minimal=True) user_input = "2 + 2" try: result = interp.eval(user_input, raise_errors=True) print(f"Result: {result}") except Exception as e: print(f"Error: {e}") ```