pax_global_header00006660000000000000000000000064147432616540014526gustar00rootroot0000000000000052 comment=40c31962bbdfe1012aacca1892a8d9263a67258e lmfit-asteval-40c3196/000077500000000000000000000000001474326165400145515ustar00rootroot00000000000000lmfit-asteval-40c3196/.codecov.yml000066400000000000000000000004661474326165400170020ustar00rootroot00000000000000codecov: token: f6004578-8b3d-4366-bcea-c229423ba532 coverage: precision: 1 range: "80...100" status: project: default: target: auto threshold: 2.0% informational: true patch: default: target: auto threshold: 10% informational: true lmfit-asteval-40c3196/.gitattributes000066400000000000000000000000411474326165400174370ustar00rootroot00000000000000asteval/_version.py export-subst lmfit-asteval-40c3196/.github/000077500000000000000000000000001474326165400161115ustar00rootroot00000000000000lmfit-asteval-40c3196/.github/dependabot.yml000066400000000000000000000011401474326165400207350ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "pip" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" allow: # Allow both direct and indirect updates for all packages - dependency-type: "all" lmfit-asteval-40c3196/.github/workflows/000077500000000000000000000000001474326165400201465ustar00rootroot00000000000000lmfit-asteval-40c3196/.github/workflows/macos_numpy.yml000066400000000000000000000012611474326165400232230ustar00rootroot00000000000000name: test on macos, with numpy on: [push] jobs: build: runs-on: macos-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install setuptools codecov pytest pytest-cov coverage numpy python -m pip install . - name: Test with pytest run: | cd tests python -m pytest lmfit-asteval-40c3196/.github/workflows/ubuntu_nonumpy.yml000066400000000000000000000013641474326165400240040ustar00rootroot00000000000000name: test on ubuntu, without numpy on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install setuptools codecov pytest pytest-cov coverage python -m pip install . - name: Test with pytest run: | cd tests python -m pytest lmfit-asteval-40c3196/.github/workflows/ubuntu_numpy.yml000066400000000000000000000020701474326165400234420ustar00rootroot00000000000000name: test on ubuntu, with numpy and numpy_financial on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] with_financial: [0, 1] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install setuptools codecov pytest pytest-cov coverage numpy - if: ${{ matrix.with_financial }} run: python -m pip install numpy_financial - name: Install this package run: | python -m pip install . - name: Test with pytest run: | cd tests python -m pytest python -m pytest --cov=./ --cov-report=xml - name: upload coverage report to codecov uses: codecov/codecov-action@v2 lmfit-asteval-40c3196/.github/workflows/windows_numpy.yml000066400000000000000000000012651474326165400236170ustar00rootroot00000000000000name: test on windows, with numpy on: [push] jobs: build: runs-on: windows-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install setuptools codecov pytest pytest-cov coverage numpy python -m pip install . - name: Test with pytest run: | cd tests python -m pytest lmfit-asteval-40c3196/.gitignore000066400000000000000000000001461474326165400165420ustar00rootroot00000000000000*.pyc *~ *# .coverage asteval/version.py NonGit/ doc/_build doc/*.pdf build dist *.egg-info MANIFEST lmfit-asteval-40c3196/LICENSE000066400000000000000000000021201474326165400155510ustar00rootroot00000000000000The MIT License Copyright (c) 2025 Matthew Newville, The University of Chicago Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lmfit-asteval-40c3196/README.rst000066400000000000000000000066751474326165400162560ustar00rootroot00000000000000ASTEVAL ======= .. image:: https://github.com/lmfit/asteval/actions/workflows/ubuntu_numpy.yml/badge.svg :target: https://github.com/lmfit/asteval/actions/workflows/ubuntu_numpy.yml .. image:: https://github.com/lmfit/asteval/actions/workflows/ubuntu_nonumpy.yml/badge.svg :target: https://github.com/lmfit/asteval/actions/workflows/ubuntu_nonumpy.yml .. image:: https://github.com/lmfit/asteval/actions/workflows/macos_numpy.yml/badge.svg :target: https://github.com/lmfit/asteval/actions/workflows/macos_numpy.yml .. image:: https://github.com/lmfit/asteval/actions/workflows/windows_numpy.yml/badge.svg :target: https://github.com/lmfit/asteval/actions/workflows/windows_numpy.yml .. image:: https://codecov.io/gh/lmfit/asteval/branch/master/graph/badge.svg :target: https://codecov.io/gh/lmfit/asteval .. image:: https://img.shields.io/pypi/v/asteval.svg :target: https://pypi.org/project/asteval .. image:: https://img.shields.io/pypi/dm/asteval.svg :target: https://pypi.org/project/asteval .. image:: https://img.shields.io/badge/docs-read-brightgreen :target: https://lmfit.github.io/asteval/ .. image:: https://zenodo.org/badge/4185/newville/asteval.svg :target: https://zenodo.org/badge/latestdoi/4185/newville/asteval Links ----- * Documentation: https://lmfit.github.io/asteval/ * PyPI installation: https://pypi.org/project/asteval/ * Development Code: https://github.com/lmfit/asteval * Issue Tracker: https://github.com/lmfit/asteval/issues Installation ------------ Use ``pip install asteval`` to install the asteval library. Asteval requires Python 3.8 or higher. If installed, many functions and constants from Numpy will be used by default. About ASTEVAL -------------- ASTEVAL is a safe(ish) evaluator of Python expressions and statements, using Python's ast module. The idea is to provide a simple, safe, and robust miniature mathematical language that can handle user input. The emphasis here is on mathematical expressions so that many functions from ``numpy`` are imported and used if available. Many Python language constructs are supported by default, These include slicing, subscripting, list comprehension, conditionals (if-elif-else blocks and if expressions), flow control (for loops, while loops, and try-except-finally blocks). All data are Python objects and built-in data structures (dictionaries, tuples, lists, Numpy arrays, strings) are fully supported by default. Many of the standard built-in Python functions are available, as are all mathematical functions from the math module. If the Numpy module is installed, many of its functions will also be available. Users can define and run their own functions within the confines of the limitations of Asteval. There are several absences and differences with Python, and Asteval is by no means an attempt to reproduce Python with its own ast module. Some of the most important differences and absences are: 1. Variable and function symbol names are held in a simple symbol table (a single dictionary), giving a flat namespace. 2. creating classes is not supported. 3. importing modules is not supported by default - it can be enabled. 4. function decorators, yield, lambda, exec, and eval are not supported. 5. files can only be opened in read-only mode. In addition, accessing many internal methods and classes of objects is forbidden in order to strengthen Asteval against malicious user code. Matt Newville Last Update: 30-June-2024 lmfit-asteval-40c3196/asteval/000077500000000000000000000000001474326165400162105ustar00rootroot00000000000000lmfit-asteval-40c3196/asteval/__init__.py000066400000000000000000000004721474326165400203240ustar00rootroot00000000000000from .version import version as __version__ from .asteval import Interpreter from .astutils import (NameFinder, get_ast_names, make_symbol_table, valid_symbol_name) __all__ = ['Interpreter', 'NameFinder', 'valid_symbol_name', 'make_symbol_table', 'get_ast_names', '__version__'] lmfit-asteval-40c3196/asteval/asteval.py000066400000000000000000001105261474326165400202260ustar00rootroot00000000000000#!/usr/bin/env python """ Safe(ish) evaluation of minimal Python code using Python's ast module. This module provides an Interpreter class that compiles a restricted set of Python expressions and statements to Python's AST representation, and then executes that representation using values held in a symbol table. The symbol table is a simple dictionary, giving a flat namespace. This comes pre-loaded with many functions from Python's builtin and math module. If numpy is installed, many numpy functions are also included. Additional symbols can be added when an Interpreter is created, but the user of that interpreter will not be able to import additional modules. Expressions, including loops, conditionals, and function definitions can be compiled into ast node and then evaluated later, using the current values in the symbol table. The result is a restricted, simplified version of Python meant for numerical calculations that is somewhat safer than 'eval' because many unsafe operations (such as 'eval') are simply not allowed, and others (such as 'import') are disabled by default, but can be explicitly enabled. Many parts of Python syntax are supported, including: for loops, while loops, if-then-elif-else conditionals, with, try-except-finally function definitions with def advanced slicing: a[::-1], array[-3:, :, ::2] if-expressions: out = one_thing if TEST else other list, dict, and set comprehension The following Python syntax elements are not supported: Import, Exec, Lambda, Class, Global, Generators, Yield, Decorators In addition, while many builtin functions are supported, several builtin functions that are considered unsafe are missing ('eval', 'exec', and 'getattr' for example) are missing. """ import ast import sys import copy import inspect import time from sys import exc_info, stderr, stdout from .astutils import (HAS_NUMPY, ExceptionHolder, ReturnedNone, Empty, make_symbol_table, numpy, op2func, safe_getattr, safe_format, valid_symbol_name, Procedure) ALL_NODES = ['arg', 'assert', 'assign', 'attribute', 'augassign', 'binop', 'boolop', 'break', 'bytes', 'call', 'compare', 'constant', 'continue', 'delete', 'dict', 'dictcomp', 'ellipsis', 'excepthandler', 'expr', 'extslice', 'for', 'functiondef', 'if', 'ifexp', 'import', 'importfrom', 'index', 'interrupt', 'list', 'listcomp', 'module', 'name', 'nameconstant', 'num', 'pass', 'raise', 'repr', 'return', 'set', 'setcomp', 'slice', 'str', 'subscript', 'try', 'tuple', 'unaryop', 'while', 'with', 'formattedvalue', 'joinedstr'] MINIMAL_CONFIG = {'import': False, 'importfrom': False} DEFAULT_CONFIG = {'import': False, 'importfrom': False} for _tnode in ('assert', 'augassign', 'delete', 'if', 'ifexp', 'for', 'formattedvalue', 'functiondef', 'print', 'raise', 'listcomp', 'dictcomp', 'setcomp', 'try', 'while', 'with'): MINIMAL_CONFIG[_tnode] = False DEFAULT_CONFIG[_tnode] = True class Interpreter: """create an asteval Interpreter: a restricted, simplified interpreter of mathematical expressions using Python syntax. Parameters ---------- symtable : dict or `None` dictionary or SymbolTable to use as symbol table (if `None`, one will be created). nested_symtable : bool, optional whether to use a new-style nested symbol table instead of a plain dict [False] user_symbols : dict or `None` dictionary of user-defined symbols to add to symbol table. writer : file-like or `None` callable file-like object where standard output will be sent. err_writer : file-like or `None` callable file-like object where standard error will be sent. use_numpy : bool whether to use functions from numpy. max_statement_length : int maximum length of expression allowed [50,000 characters] readonly_symbols : iterable or `None` symbols that the user can not assign to builtins_readonly : bool whether to blacklist all symbols that are in the initial symtable minimal : bool create a minimal interpreter: disable many nodes (see Note 1). config : dict dictionay listing which nodes to support (see note 2)) 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', 'listcomp', 'dictcomp', 'setcomp', 'augassign', 'assert', 'delete', 'raise', 'print') 2. by default 'import' and 'importfrom' are disabled, though they can be enabled. """ def __init__(self, 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): self.config = copy.copy(MINIMAL_CONFIG if minimal else DEFAULT_CONFIG) if config is not None: self.config.update(config) self.config['nested_symtable'] = nested_symtable if user_symbols is None: user_symbols = {} if 'usersyms' in kws: user_symbols = kws.pop('usersyms') # back compat, changed July, 2023, v 0.9.4 if len(kws) > 0: for key, val in kws.items(): if key.startswith('no_'): node = key[3:] if node in ALL_NODES: self.config[node] = not val elif key.startswith('with_'): node = key[5:] if node in ALL_NODES: self.config[node] = val self.writer = writer or stdout self.err_writer = err_writer or stderr self.max_statement_length = max(1, min(1.e8, max_statement_length)) self.use_numpy = HAS_NUMPY and use_numpy if symtable is None: symtable = make_symbol_table(nested=nested_symtable, use_numpy=self.use_numpy, **user_symbols) symtable['print'] = self._printer self.symtable = symtable self._interrupt = None self.error = [] self.error_msg = None self.expr = None self.retval = None self._calldepth = 0 self.lineno = 0 self.code_text = [] self.start_time = time.time() self.node_handlers = {} for node in ALL_NODES: handler = self.unimplemented if self.config.get(node, True): handler = getattr(self, f"on_{node}", self.unimplemented) self.node_handlers[node] = handler # to rationalize try/except try/finally if 'try' in self.node_handlers: self.node_handlers['tryexcept'] = self.node_handlers['try'] self.node_handlers['tryfinally'] = self.node_handlers['try'] if readonly_symbols is None: self.readonly_symbols = set() else: self.readonly_symbols = set(readonly_symbols) if builtins_readonly: self.readonly_symbols |= set(self.symtable) self.no_deepcopy = [key for key, val in symtable.items() if (callable(val) or inspect.ismodule(val) or 'numpy.lib.index_tricks' in repr(type(val)))] def remove_nodehandler(self, node): """remove support for a node returns current node handler, so that it might be re-added with add_nodehandler() """ out = None if node in self.node_handlers: out = self.node_handlers.pop(node) return out def set_nodehandler(self, node, handler=None): """set node handler or use current built-in default""" if handler is None: handler = getattr(self, f"on_{node}", self.unimplemented) self.node_handlers[node] = handler return handler def user_defined_symbols(self): """Return a set of symbols that have been added to symtable after construction. I.e., the symbols from self.symtable that are not in self.no_deepcopy. Returns ------- unique_symbols : set symbols in symtable that are not in self.no_deepcopy """ sym_in_current = set(self.symtable.keys()) sym_from_construction = set(self.no_deepcopy) unique_symbols = sym_in_current.difference(sym_from_construction) return unique_symbols def unimplemented(self, node): """Unimplemented nodes.""" msg = f"{node.__class__.__name__} not supported" self.raise_exception(node, exc=NotImplementedError, msg=msg) def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None): """Add an exception.""" if expr is not None: self.expr = expr msg = str(msg) text = self.expr if len(self.code_text) > 0: text = self.code_text[-1] err = ExceptionHolder(node, exc=exc, msg=msg, expr=self.expr, text=text, lineno=lineno) self._interrupt = ast.Raise() self.error.append(err) if self.error_msg is None: self.error_msg = msg elif len(msg) > 0: pass # if err.exc is not None: # self.error_msg = f"{err.exc.__name__}: {msg}" if exc is None: exc = self.error[-1].exc if exc is None and len(self.error) > 0: while exc is None and len(self.error) > 0: err = self.error.pop() exc = err.exc if exc is None: exc = Exception if len(err.msg) == 0 and len(self.error_msg) == 0 and len(self.error) > 1: err = self.error.pop(-1) raise err.exc(err.msg) else: if len(err.msg) == 0: err.msg = self.error_msg raise exc(self.error_msg) # main entry point for Ast node evaluation # parse: text of statements -> ast # run: ast -> result # eval: string statement -> result = run(parse(statement)) def parse(self, text): """Parse statement/expression to Ast representation.""" if len(text) > self.max_statement_length: msg = f'length of text exceeds {self.max_statement_length:d} characters' self.raise_exception(None, exc=RuntimeError, expr=msg) self.expr = text try: out = ast.parse(text) except SyntaxError: self.raise_exception(None, exc=SyntaxError, expr=text) except: self.raise_exception(None, exc=RuntimeError, expr=text) out = ast.fix_missing_locations(out) return out def run(self, node, expr=None, lineno=None, with_raise=True): """Execute parsed Ast representation for an expression.""" # Note: keep the 'node is None' test: internal code here may run # run(None) and expect a None in return. if isinstance(node, str): return self.eval(node, raise_errors=with_raise) out = None if len(self.error) > 0: return out if self.retval is not None: return self.retval if isinstance(self._interrupt, (ast.Break, ast.Continue)): return self._interrupt if node is None: return out if lineno is not None: self.lineno = lineno if expr is not None: self.expr = expr self.code_text.append(expr) # get handler for this node: # on_xxx with handle nodes of type 'xxx', etc try: handler = self.node_handlers[node.__class__.__name__.lower()] except KeyError: self.raise_exception(None, exc=NotImplementedError, expr=self.expr) # run the handler: this will likely generate # recursive calls into this run method. try: ret = handler(node) if isinstance(ret, enumerate): ret = list(ret) return ret except: if with_raise and self.expr is not None: self.raise_exception(node, expr=self.expr) # avoid too many repeated error messages (yes, this needs to be "2") if len(self.error) > 2: self._remove_duplicate_errors() return None def _remove_duplicate_errors(self): """remove duplicate exceptions""" error = [self.error[0]] for err in self.error[1:]: lerr = error[-1] if err.exc != lerr.exc or err.expr != lerr.expr or err.msg != lerr.msg: if isinstance(err.msg, str) and len(err.msg) > 0: error.append(err) self.error = error def __call__(self, expr, **kw): """Call class instance as function.""" return self.eval(expr, **kw) def eval(self, expr, lineno=0, show_errors=True, raise_errors=False): """Evaluate a single statement.""" self.lineno = lineno self.error = [] self.error_msg = None self.start_time = time.time() if isinstance(expr, str): try: node = self.parse(expr) except Exception: errmsg = exc_info()[1] if len(self.error) > 0: lerr = self.error[-1] errmsg = lerr.get_error()[1] if raise_errors: raise lerr.exc(errmsg) if show_errors: print(errmsg, file=self.err_writer) return None else: node = expr try: return self.run(node, expr=expr, lineno=lineno, with_raise=raise_errors) except Exception: if show_errors and not raise_errors: errmsg = exc_info()[1] if len(self.error) > 0: errmsg = self.error[-1].get_error()[1] print(errmsg, file=self.err_writer) if raise_errors and len(self.error) > 0: self._remove_duplicate_errors() err = self.error[-1] raise err.exc(err.get_error()[1]) return None @staticmethod def dump(node, **kw): """Simple ast dumper.""" return ast.dump(node, **kw) # handlers for ast components def on_expr(self, node): """Expression.""" return self.run(node.value) # ('value',) # imports def on_import(self, node): # ('names',) "simple import" for tnode in node.names: self.import_module(tnode.name, tnode.asname) def on_importfrom(self, node): # ('module', 'names', 'level') "import/from" fromlist, asname = [], [] for tnode in node.names: fromlist.append(tnode.name) asname.append(tnode.asname) self.import_module(node.module, asname, fromlist=fromlist) def import_module(self, name, asname, fromlist=None): """import a python module, installing it into the symbol table. options: name name of module to import 'foo' in 'import foo' asname alias for imported name(s) 'bar' in 'import foo as bar' or ['s','t'] in 'from foo import x as s, y as t' fromlist list of symbols to import with 'from-import' ['x','y'] in 'from foo import x, y' """ # find module in sys.modules or import to it if name in sys.modules: thismod = sys.modules[name] else: try: __import__(name) thismod = sys.modules[name] except: self.raise_exception(None, exc=ImportError, msg='Import Error') if fromlist is None: if asname is not None: self.symtable[asname] = sys.modules[name] else: mparts = [] parts = name.split('.') while len(parts) > 0: mparts.append(parts.pop(0)) modname = '.'.join(mparts) inname = name if (len(parts) == 0) else modname self.symtable[inname] = sys.modules[modname] else: # import-from construct if asname is None: asname = [None]*len(fromlist) for sym, alias in zip(fromlist, asname): if alias is None: alias = sym self.symtable[alias] = getattr(thismod, sym) def on_index(self, node): """Index.""" return self.run(node.value) # ('value',) def on_return(self, node): # ('value',) """Return statement: look for None, return special sentinel.""" if self._calldepth == 0: raise SyntaxError('cannot return at top level') self.retval = self.run(node.value) if self.retval is None: self.retval = ReturnedNone def on_repr(self, node): """Repr.""" return repr(self.run(node.value)) # ('value',) def on_module(self, node): # ():('body',) """Module def.""" out = None for tnode in node.body: out = self.run(tnode) return out def on_expression(self, node): "basic expression" return self.on_module(node) # ():('body',) def on_pass(self, node): """Pass statement.""" return None # () # for break and continue: set the instance variable _interrupt def on_interrupt(self, node): # () """Interrupt handler.""" self._interrupt = node return node def on_break(self, node): """Break.""" return self.on_interrupt(node) def on_continue(self, node): """Continue.""" return self.on_interrupt(node) def on_assert(self, node): # ('test', 'msg') """Assert statement.""" if not self.run(node.test): msg = node.msg.value if node.msg else "" # msg = node.msg.s if node.msg else "" self.raise_exception(node, exc=AssertionError, msg=msg) return True def on_list(self, node): # ('elt', 'ctx') """List.""" return [self.run(e) for e in node.elts] def on_tuple(self, node): # ('elts', 'ctx') """Tuple.""" return tuple(self.on_list(node)) def on_set(self, node): # ('elts') """Set.""" return set([self.run(k) for k in node.elts]) def on_dict(self, node): # ('keys', 'values') """Dictionary.""" return {self.run(k): self.run(v) for k, v in zip(node.keys, node.values)} def on_constant(self, node): # ('value', 'kind') """Return constant value.""" return node.value def on_joinedstr(self, node): # ('values',) "join strings, used in f-strings" return ''.join([self.run(k) for k in node.values]) def on_formattedvalue(self, node): # ('value', 'conversion', 'format_spec') "formatting used in f-strings" val = self.run(node.value) fstring_converters = {115: str, 114: repr, 97: ascii} if node.conversion in fstring_converters: val = fstring_converters[node.conversion](val) fmt = '{__fstring__}' if node.format_spec is not None: fmt = f'{{__fstring__:{self.run(node.format_spec)}}}' return safe_format(fmt, self.raise_exception, node, __fstring__=val) def _getsym(self, node): val = self.symtable.get(node.id, ReturnedNone) if isinstance(val, Empty): msg = f"name '{node.id}' is not defined" self.raise_exception(node, exc=NameError, msg=msg) return val def on_name(self, node): # ('id', 'ctx') """Name node.""" ctx = node.ctx.__class__ if ctx in (ast.Param, ast.Del): return str(node.id) return self._getsym(node) def node_assign(self, node, val): """Assign a value (not the node.value object) to a node. This is used by on_assign, but also by for, list comprehension, etc. """ if node.__class__ == ast.Name: if (not valid_symbol_name(node.id) or node.id in self.readonly_symbols): errmsg = f"invalid symbol name (reserved word?) {node.id}" self.raise_exception(node, exc=NameError, msg=errmsg) self.symtable[node.id] = val if node.id in self.no_deepcopy: self.no_deepcopy.remove(node.id) elif node.__class__ == ast.Attribute: if node.ctx.__class__ == ast.Load: msg = f"cannot assign to attribute {node.attr}" self.raise_exception(node, exc=AttributeError, msg=msg) setattr(self.run(node.value), node.attr, val) elif node.__class__ == ast.Subscript: self.run(node.value)[self.run(node.slice)] = val elif node.__class__ in (ast.Tuple, ast.List): if len(val) == len(node.elts): for telem, tval in zip(node.elts, val): self.node_assign(telem, tval) else: raise ValueError('too many values to unpack') def on_attribute(self, node): # ('value', 'attr', 'ctx') """Extract attribute.""" ctx = node.ctx.__class__ if ctx == ast.Store: msg = "attribute for storage: shouldn't be here!" self.raise_exception(node, exc=RuntimeError, msg=msg) sym = self.run(node.value) if ctx == ast.Del: return delattr(sym, node.attr) return safe_getattr(sym, node.attr, self.raise_exception, node) def on_assign(self, node): # ('targets', 'value') """Simple assignment.""" val = self.run(node.value) for tnode in node.targets: self.node_assign(tnode, val) def on_augassign(self, node): # ('target', 'op', 'value') """Augmented assign.""" return self.on_assign(ast.Assign(targets=[node.target], value=ast.BinOp(left=node.target, op=node.op, right=node.value))) def on_slice(self, node): # ():('lower', 'upper', 'step') """Simple slice.""" return slice(self.run(node.lower), self.run(node.upper), self.run(node.step)) def on_extslice(self, node): # ():('dims',) """Extended slice.""" return tuple([self.run(tnode) for tnode in node.dims]) def on_subscript(self, node): # ('value', 'slice', 'ctx') """Subscript handling""" return self.run(node.value)[self.run(node.slice)] def on_delete(self, node): # ('targets',) """Delete statement.""" for tnode in node.targets: if tnode.ctx.__class__ != ast.Del: break children = [] while tnode.__class__ == ast.Attribute: children.append(tnode.attr) tnode = tnode.value if (tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols): children.append(tnode.id) children.reverse() self.symtable.pop('.'.join(children)) elif tnode.__class__ == ast.Subscript: nslice = self.run(tnode.slice) children = [] tnode = tnode.value while tnode.__class__ == ast.Attribute: children.append(tnode.attr) tnode = tnode.value if (tnode.__class__ == ast.Name and not tnode.id in self.readonly_symbols): children.append(tnode.id) children.reverse() sname = '.'.join(children) val = self.run(sname) del val[nslice] if len(children) == 1: self.symtable[sname] = val else: child = self.symtable[children[0]] for cname in children[1:-1]: child = child[cname] setattr(child, children[-1], val) def on_unaryop(self, node): # ('op', 'operand') """Unary operator.""" return op2func(node.op)(self.run(node.operand)) def on_binop(self, node): # ('left', 'op', 'right') """Binary operator.""" return op2func(node.op)(self.run(node.left), self.run(node.right)) def on_boolop(self, node): # ('op', 'values') """Boolean operator.""" val = self.run(node.values[0]) is_and = ast.And == node.op.__class__ if (is_and and val) or (not is_and and not val): for nodeval in node.values[1:]: val = op2func(node.op)(val, self.run(nodeval)) if (is_and and not val) or (not is_and and val): break return val def on_compare(self, node): # ('left', 'ops', 'comparators') """comparison operators, including chained comparisons (a 1 for oper, rnode in zip(node.ops, node.comparators): rval = self.run(rnode) ret = op2func(oper)(lval, rval) if multi: results.append(ret) if not all(results): return False lval = rval if multi: ret = all(results) return ret def _printer(self, *out, **kws): """Generic print function.""" if self.config.get('print', True): flush = kws.pop('flush', True) fileh = kws.pop('file', self.writer) sep = kws.pop('sep', ' ') end = kws.pop('sep', '\n') print(*out, file=fileh, sep=sep, end=end) if flush: fileh.flush() def on_if(self, node): # ('test', 'body', 'orelse') """Regular if-then-else statement.""" block = node.body if not self.run(node.test): block = node.orelse for tnode in block: self.run(tnode) def on_ifexp(self, node): # ('test', 'body', 'orelse') """If expressions.""" expr = node.orelse if self.run(node.test): expr = node.body return self.run(expr) def on_while(self, node): # ('test', 'body', 'orelse') """While blocks.""" while self.run(node.test): self._interrupt = None for tnode in node.body: self.run(tnode) if self._interrupt is not None: break if isinstance(self._interrupt, ast.Break): break else: for tnode in node.orelse: self.run(tnode) self._interrupt = None def on_for(self, node): # ('target', 'iter', 'body', 'orelse') """For blocks.""" for val in self.run(node.iter): self.node_assign(node.target, val) self._interrupt = None for tnode in node.body: self.run(tnode) if self._interrupt is not None: break if isinstance(self._interrupt, ast.Break): break else: for tnode in node.orelse: self.run(tnode) self._interrupt = None def on_with(self, node): # ('items', 'body', 'type_comment') """with blocks.""" contexts = [] for item in node.items: ctx = self.run(item.context_expr) contexts.append(ctx) if hasattr(ctx, '__enter__'): result = ctx.__enter__() if item.optional_vars is not None: self.node_assign(item.optional_vars, result) else: msg = "object does not support the context manager protocol" raise TypeError(f"'{type(ctx)}' {msg}") for bnode in node.body: self.run(bnode) if self._interrupt is not None: break for ctx in contexts: if hasattr(ctx, '__exit__'): ctx.__exit__() def _comp_save_syms(self, node): """find and save symbols that will be used in a comprehension""" saved_syms = {} for tnode in node.generators: if tnode.target.__class__ == ast.Name: if (not valid_symbol_name(tnode.target.id) or tnode.target.id in self.readonly_symbols): errmsg = f"invalid symbol name (reserved word?) {tnode.target.id}" self.raise_exception(tnode.target, exc=NameError, msg=errmsg) if tnode.target.id in self.symtable: saved_syms[tnode.target.id] = copy.deepcopy(self._getsym(tnode.target)) elif tnode.target.__class__ == ast.Tuple: for tval in tnode.target.elts: if tval.id in self.symtable: saved_syms[tval.id] = copy.deepcopy(self._getsym(tval)) return saved_syms def do_generator(self, gnodes, node, out): """general purpose generator """ gnode = gnodes[0] nametype = True target = None if gnode.target.__class__ == ast.Name: if (not valid_symbol_name(gnode.target.id) or gnode.target.id in self.readonly_symbols): errmsg = f"invalid symbol name (reserved word?) {gnode.target.id}" self.raise_exception(gnode.target, exc=NameError, msg=errmsg) target = gnode.target.id elif gnode.target.__class__ == ast.Tuple: nametype = False target = tuple([gval.id for gval in gnode.target.elts]) for val in self.run(gnode.iter): if nametype and target is not None: self.symtable[target] = val else: for telem, tval in zip(target, val): self.symtable[telem] = tval add = True for cond in gnode.ifs: add = add and self.run(cond) if not add: break if add: if len(gnodes) > 1: self.do_generator(gnodes[1:], node, out) elif isinstance(out, list): out.append(self.run(node.elt)) elif isinstance(out, dict): out[self.run(node.key)] = self.run(node.value) def on_listcomp(self, node): """List comprehension v2""" saved_syms = self._comp_save_syms(node) out = [] self.do_generator(node.generators, node, out) for name, val in saved_syms.items(): self.symtable[name] = val return out def on_setcomp(self, node): """Set comprehension""" return set(self.on_listcomp(node)) def on_dictcomp(self, node): """Dict comprehension v2""" saved_syms = self._comp_save_syms(node) out = {} self.do_generator(node.generators, node, out) for name, val in saved_syms.items(): self.symtable[name] = val return out def on_excepthandler(self, node): # ('type', 'name', 'body') """Exception handler...""" return (self.run(node.type), node.name, node.body) def on_try(self, node): # ('body', 'handlers', 'orelse', 'finalbody') """Try/except/else/finally blocks.""" no_errors = True for tnode in node.body: self.run(tnode, with_raise=False) no_errors = no_errors and len(self.error) == 0 if len(self.error) > 0: e_type, e_value, _ = self.error[-1].exc_info for hnd in node.handlers: htype = None if hnd.type is not None: htype = __builtins__.get(hnd.type.id, None) if htype is None or isinstance(e_type(), htype): self.error = [] if hnd.name is not None: self.symtable[hnd.name] = e_value for tline in hnd.body: self.run(tline) break break if no_errors and hasattr(node, 'orelse'): for tnode in node.orelse: self.run(tnode) if hasattr(node, 'finalbody'): for tnode in node.finalbody: self.run(tnode) def on_raise(self, node): # ('type', 'inst', 'tback') """Raise statement: note difference for python 2 and 3.""" excnode = node.exc msgnode = node.cause out = self.run(excnode) msg = ' '.join(out.args) msg2 = self.run(msgnode) if msg2 not in (None, 'None'): msg = f"{msg:s}: {msg2:s}" self.raise_exception(None, exc=out.__class__, msg=msg, expr='') def on_call(self, node): """Function execution.""" func = self.run(node.func) if not hasattr(func, '__call__') and not isinstance(func, type): msg = f"'{func}' is not callable!!" self.raise_exception(node, exc=TypeError, msg=msg) args = [self.run(targ) for targ in node.args] starargs = getattr(node, 'starargs', None) if starargs is not None: args = args + self.run(starargs) keywords = {} if func == print: keywords['file'] = self.writer for key in node.keywords: if not isinstance(key, ast.keyword): msg = f"keyword error in function call '{func}'" self.raise_exception(node, msg=msg) if key.arg is None: keywords.update(self.run(key.value)) elif key.arg in keywords: self.raise_exception(node, exc=SyntaxError, msg=f"keyword argument repeated: {key.arg}") else: keywords[key.arg] = self.run(key.value) kwargs = getattr(node, 'kwargs', None) if kwargs is not None: keywords.update(self.run(kwargs)) if isinstance(func, Procedure): self._calldepth += 1 try: out = func(*args, **keywords) except Exception as ex: out = None func_name = getattr(func, '__name__', str(func)) msg = f"Error running function '{func_name}' with args '{args}'" msg = f"{msg} and kwargs {keywords}: {ex}" self.raise_exception(node, msg=msg) finally: if isinstance(func, Procedure): self._calldepth -= 1 return out def on_arg(self, node): # ('test', 'msg') """Arg for function definitions.""" return node.arg def on_functiondef(self, node): """Define procedures.""" # ('name', 'args', 'body', 'decorator_list') if node.decorator_list: raise Warning("decorated procedures not supported!") kwargs = [] if (not valid_symbol_name(node.name) or node.name in self.readonly_symbols): errmsg = f"invalid function name (reserved word?) {node.name}" self.raise_exception(node, exc=NameError, msg=errmsg) offset = len(node.args.args) - len(node.args.defaults) for idef, defnode in enumerate(node.args.defaults): defval = self.run(defnode) keyval = self.run(node.args.args[idef+offset]) kwargs.append((keyval, defval)) args = [tnode.arg for tnode in node.args.args[:offset]] doc = None nb0 = node.body[0] if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Constant): doc = nb0.value varkws = node.args.kwarg vararg = node.args.vararg if isinstance(vararg, ast.arg): vararg = vararg.arg if isinstance(varkws, ast.arg): varkws = varkws.arg self.symtable[node.name] = Procedure(node.name, self, doc=doc, lineno=self.lineno, body=node.body, text=ast.unparse(node), args=args, kwargs=kwargs, vararg=vararg, varkws=varkws) if node.name in self.no_deepcopy: self.no_deepcopy.remove(node.name) lmfit-asteval-40c3196/asteval/astutils.py000066400000000000000000000657501474326165400204470ustar00rootroot00000000000000""" utility functions for asteval Matthew Newville , The University of Chicago """ import ast import io import math import numbers import re from sys import exc_info from tokenize import ENCODING as tk_ENCODING from tokenize import NAME as tk_NAME from tokenize import tokenize as generate_tokens from string import Formatter builtins = __builtins__ if not isinstance(builtins, dict): builtins = builtins.__dict__ HAS_NUMPY = False try: import numpy numpy_version = numpy.version.version.split('.', 2) HAS_NUMPY = True except ImportError: numpy = None HAS_NUMPY_FINANCIAL = False try: import numpy_financial HAS_NUMPY_FINANCIAL = True except ImportError: pass # This is a necessary API but it's undocumented and moved around # between Python releases try: from _string import formatter_field_name_split except ImportError: formatter_field_name_split = lambda \ x: x._formatter_field_name_split() MAX_EXPONENT = 10000 MAX_STR_LEN = 2 << 17 # 256KiB MAX_SHIFT = 1000 MAX_OPEN_BUFFER = 2 << 17 RESERVED_WORDS = ('False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', 'exec', 'eval', 'execfile', '__import__', '__package__', '__fstring__') NAME_MATCH = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$").match # unsafe attributes for all objects: UNSAFE_ATTRS = ('__subclasses__', '__bases__', '__globals__', '__code__', '__reduce__', '__reduce_ex__', '__mro__', '__closure__', '__func__', '__self__', '__module__', '__dict__', '__class__', '__call__', '__get__', '__getattribute__', '__subclasshook__', '__new__', '__init__', 'func_globals', 'func_code', 'func_closure', 'im_class', 'im_func', 'im_self', 'gi_code', 'gi_frame', 'f_locals', '__asteval__','mro') # unsafe attributes for particular objects, by type UNSAFE_ATTRS_DTYPES = {str: ('format', 'format_map')} # inherit these from python's __builtins__ FROM_PY = ('ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplementedError', 'OSError', 'OverflowError', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'ValueError', 'Warning', 'ZeroDivisionError', 'abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'bytes', 'chr', 'complex', 'dict', 'dir', 'divmod', 'enumerate', 'filter', 'float', 'format', 'frozenset', 'hash', 'hex', 'id', 'int', 'isinstance', 'len', 'list', 'map', 'max', 'min', 'oct', 'ord', 'pow', 'range', 'repr', 'reversed', 'round', 'set', 'slice', 'sorted', 'str', 'sum', 'tuple', 'zip') BUILTINS_TABLE = {sym: builtins[sym] for sym in FROM_PY if sym in builtins} # inherit these from python's math FROM_MATH = ('acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc') MATH_TABLE = {sym: getattr(math, sym) for sym in FROM_MATH if hasattr(math, sym)} FROM_NUMPY = ('abs', 'add', 'all', 'amax', 'amin', 'angle', 'any', 'append', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'argwhere', 'around', 'array', 'asarray', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'broadcast', 'ceil', 'choose', 'clip', 'column_stack', 'common_type', 'complex128', 'compress', 'concatenate', 'conjugate', 'convolve', 'copysign', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov', 'cross', 'cumprod', 'cumsum', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'divide', 'dot', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'empty', 'empty_like', 'equal', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fill_diagonal', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'fliplr', 'flipud', 'float64', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'genfromtxt', 'getbufsize', 'geterr', 'gradient', 'greater', 'greater_equal', 'hamming', 'hanning', 'histogram', 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'indices', 'inexact', 'inf', 'info', 'inner', 'insert', 'int32', 'integer', 'interp', 'intersect1d', 'invert', 'iscomplex', 'iscomplexobj', 'isfinite', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'iterable', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'linspace', 'little_endian', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longdouble', 'longlong', 'mask_indices', 'matrix', 'maximum', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum', 'ndarray', 'ndenumerate', 'ndim', 'ndindex', 'negative', 'nextafter', 'nonzero', 'not_equal', 'number', 'ones', 'ones_like', 'outer', 'packbits', 'percentile', 'pi', 'piecewise', 'place', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'prod', 'ptp', 'put', 'putmask', 'rad2deg', 'radians', 'ravel', 'real', 'real_if_close', 'reciprocal', 'record', 'remainder', 'repeat', 'reshape', 'resize', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'searchsorted', 'select', 'setbufsize', 'setdiff1d', 'seterr', 'setxor1d', 'shape', 'short', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'sinh', 'size', 'sort', 'sort_complex', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'std', 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot', 'tile', 'trace', 'transpose', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'ubyte', 'uint', 'uint32', 'union1d', 'unique', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'vsplit', 'vstack', 'where', 'zeros', 'zeros_like') FROM_NUMPY_FINANCIAL = ('fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt', 'ppmt', 'pv', 'rate') NUMPY_RENAMES = {'ln': 'log', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'acosh': 'arccosh', 'asinh': 'arcsinh'} if HAS_NUMPY: FROM_NUMPY = tuple(set(FROM_NUMPY)) FROM_NUMPY = tuple(sym for sym in FROM_NUMPY if hasattr(numpy, sym)) NUMPY_RENAMES = {sym: value for sym, value in NUMPY_RENAMES.items() if hasattr(numpy, value)} NUMPY_TABLE = {} for sym in FROM_NUMPY: obj = getattr(numpy, sym, None) if obj is not None: NUMPY_TABLE[sym] = obj for sname, sym in NUMPY_RENAMES.items(): obj = getattr(numpy, sym, None) if obj is not None: NUMPY_TABLE[sname] = obj if HAS_NUMPY_FINANCIAL: for sym in FROM_NUMPY_FINANCIAL: obj = getattr(numpy_financial, sym, None) if obj is not None: NUMPY_TABLE[sym] = obj else: NUMPY_TABLE = {} def _open(filename, mode='r', buffering=-1, encoding=None): """read only version of open()""" if mode not in ('r', 'rb', 'rU'): raise RuntimeError("Invalid open file mode, must be 'r', 'rb', or 'rU'") if buffering > MAX_OPEN_BUFFER: raise RuntimeError(f"Invalid buffering value, max buffer size is {MAX_OPEN_BUFFER}") return open(filename, mode, buffering, encoding=encoding) def _type(x): """type that prevents varargs and varkws""" return type(x).__name__ LOCALFUNCS = {'open': _open, 'type': _type} # Safe versions of functions to prevent denial of service issues def safe_pow(base, exp): """safe version of pow""" if isinstance(exp, numbers.Number): if exp > MAX_EXPONENT: raise RuntimeError(f"Invalid exponent, max exponent is {MAX_EXPONENT}") elif HAS_NUMPY and isinstance(exp, numpy.ndarray): if numpy.nanmax(exp) > MAX_EXPONENT: raise RuntimeError(f"Invalid exponent, max exponent is {MAX_EXPONENT}") return base ** exp def safe_mult(arg1, arg2): """safe version of multiply""" if isinstance(arg1, str) and isinstance(arg2, int) and len(arg1) * arg2 > MAX_STR_LEN: raise RuntimeError(f"String length exceeded, max string length is {MAX_STR_LEN}") return arg1 * arg2 def safe_add(arg1, arg2): """safe version of add""" if isinstance(arg1, str) and isinstance(arg2, str) and len(arg1) + len(arg2) > MAX_STR_LEN: raise RuntimeError(f"String length exceeded, max string length is {MAX_STR_LEN}") return arg1 + arg2 def safe_lshift(arg1, arg2): """safe version of lshift""" if isinstance(arg2, numbers.Number): if arg2 > MAX_SHIFT: raise RuntimeError(f"Invalid left shift, max left shift is {MAX_SHIFT}") elif HAS_NUMPY and isinstance(arg2, numpy.ndarray): if numpy.nanmax(arg2) > MAX_SHIFT: raise RuntimeError(f"Invalid left shift, max left shift is {MAX_SHIFT}") return arg1 << arg2 OPERATORS = {ast.Is: lambda a, b: a is b, ast.IsNot: lambda a, b: a is not b, ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b, ast.Add: safe_add, ast.BitAnd: lambda a, b: a & b, ast.BitOr: lambda a, b: a | b, ast.BitXor: lambda a, b: a ^ b, ast.Div: lambda a, b: a / b, ast.FloorDiv: lambda a, b: a // b, ast.LShift: safe_lshift, ast.RShift: lambda a, b: a >> b, ast.Mult: safe_mult, ast.Pow: safe_pow, ast.MatMult: lambda a, b: a @ b, ast.Sub: lambda a, b: a - b, ast.Mod: lambda a, b: a % b, ast.And: lambda a, b: a and b, ast.Or: lambda a, b: a or b, ast.Eq: lambda a, b: a == b, ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b, ast.Lt: lambda a, b: a < b, ast.LtE: lambda a, b: a <= b, ast.NotEq: lambda a, b: a != b, ast.Invert: lambda a: ~a, ast.Not: lambda a: not a, ast.UAdd: lambda a: +a, ast.USub: lambda a: -a} # Safe version of getattr def safe_getattr(obj, attr, raise_exc, node): """safe version of getattr""" unsafe = (attr in UNSAFE_ATTRS or (attr.startswith('__') and attr.endswith('__'))) if not unsafe: for dtype, attrlist in UNSAFE_ATTRS_DTYPES.items(): unsafe = (isinstance(obj, dtype) or obj is dtype) and attr in attrlist if unsafe: break if unsafe: msg = f"no safe attribute '{attr}' for {repr(obj)}" raise_exc(node, exc=AttributeError, msg=msg) else: try: return getattr(obj, attr) except AttributeError: pass class SafeFormatter(Formatter): def __init__(self, raise_exc, node): self.raise_exc = raise_exc self.node = node super().__init__() def get_field(self, field_name, args, kwargs): first, rest = formatter_field_name_split(field_name) obj = self.get_value(first, args, kwargs) for is_attr, i in rest: if is_attr: obj = safe_getattr(obj, i, self.raise_exc, self.node) else: obj = obj[i] return obj, first def safe_format(_string, raise_exc, node, *args, **kwargs): formatter = SafeFormatter(raise_exc, node) return formatter.vformat(_string, args, kwargs) def valid_symbol_name(name): """Determine whether the input symbol name is a valid name. Arguments --------- name : str name to check for validity. Returns -------- valid : bool whether name is a a valid symbol name This checks for Python reserved words and that the name matches the regular expression ``[a-zA-Z_][a-zA-Z0-9_]`` """ if name in RESERVED_WORDS: return False gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline) typ, _, start, end, _ = next(gen) if typ == tk_ENCODING: typ, _, start, end, _ = next(gen) return typ == tk_NAME and start == (1, 0) and end == (1, len(name)) def op2func(oper): """Return function for operator nodes.""" return OPERATORS[oper.__class__] class Empty: """Empty class.""" def __init__(self): """TODO: docstring in public method.""" return def __nonzero__(self): """Empty is TODO: docstring in magic method.""" return False def __repr__(self): """Empty is TODO: docstring in magic method.""" return "Empty" ReturnedNone = Empty() class ExceptionHolder: """Basic exception handler.""" def __init__(self, node, exc=None, msg='', expr=None, text=None, lineno=None): """TODO: docstring in public method.""" self.node = node self.expr = expr self.msg = msg self.exc = exc self.text = text self.lineno = lineno self.end_lineno = lineno self.col_offset = 0 if lineno is None: try: self.lineno = node.lineno self.end_lineno = node.end_lineno self.col_offset = node.col_offset except: pass self.exc_info = exc_info() if self.exc is None and self.exc_info[0] is not None: self.exc = self.exc_info[0] if self.msg == '' and self.exc_info[1] is not None: self.msg = str(self.exc_info[1]) def get_error(self): """Retrieve error data.""" try: exc_name = self.exc.__name__ except AttributeError: exc_name = str(self.exc) if exc_name in (None, 'None'): exc_name = 'UnknownError' out = [] self.code = [f'{l}' for l in self.text.split('\n')] self.codelines = [f'{i+1}: {l}' for i, l in enumerate(self.code)] try: out.append('\n'.join(self.code[self.lineno-1:self.end_lineno])) except: out.append(f"{self.expr}") if self.col_offset > 0: out.append(f"{self.col_offset*' '}^^^^") out.append(f"{exc_name}: {self.msg}") return (exc_name, '\n'.join(out)) def __repr__(self): return f"ExceptionHolder({self.exc}, {self.msg})" class NameFinder(ast.NodeVisitor): """Find all symbol names used by a parsed node.""" def __init__(self): """TODO: docstring in public method.""" self.names = [] ast.NodeVisitor.__init__(self) def generic_visit(self, node): """TODO: docstring in public method.""" if node.__class__.__name__ == 'Name': if node.id not in self.names: self.names.append(node.id) ast.NodeVisitor.generic_visit(self, node) def get_ast_names(astnode): """Return symbol Names from an AST node.""" finder = NameFinder() finder.generic_visit(astnode) return finder.names def valid_varname(name): "is this a valid variable name" return name.isidentifier() and name not in RESERVED_WORDS class Group(dict): """ Group: a container of objects that can be accessed either as an object attributes or dictionary key/value. Attribute names must follow Python naming conventions. """ def __init__(self, name=None, searchgroups=None, **kws): if name is None: name = hex(id(self)) self.__name__ = name dict.__init__(self, **kws) self._searchgroups = searchgroups def __setattr__(self, name, value): if not valid_varname(name): raise SyntaxError(f"invalid attribute name '{name}'") self[name] = value def __getattr__(self, name, default=None): if name in self: return self[name] if default is not None: return default raise KeyError(f"no attribute named '{name}'") def __setitem__(self, name, value): if valid_varname(name): dict.__setitem__(self, name, value) else: # raise SyntaxError(f"invalid attribute name '{name}'") return setattr(self, name, value) def get(self, key, default=None): val = self.__getattr__(key, ReturnedNone) if not isinstance(val, Empty): return val searchgroups = self._searchgroups if searchgroups is not None: for sgroup in searchgroups: grp = self.__getattr__(sgroup, None) if isinstance(grp, (Group, dict)): val = grp.__getattr__(key, ReturnedNone) if not isinstance(val, Empty): return val return default def __repr__(self): keys = [a for a in self.keys() if a != '__name__'] return f"Group('{self.__name__}', {len(keys)} symbols)" def _repr_html_(self): """HTML representation for Jupyter notebook""" html = [f"", ""] for key, val in self.items(): html.append(f""" """) html.append("
Group('{self.__name__}')
AttributeDataTypeValue
{key}{type(val).__name__} {repr(val):.75s}
") return '\n'.join(html) def make_symbol_table(use_numpy=True, nested=False, top=True, **kws): """Create a default symboltable, taking dict of user-defined symbols. Arguments --------- numpy : bool, optional whether to include symbols from numpy [True] nested : bool, optional whether to make a "new-style" nested table instead of a plain dict [False] top : bool, optional whether this is the top-level table in a nested-table [True] kws : optional additional symbol name, value pairs to include in symbol table Returns -------- symbol_table : dict or nested Group a symbol table that can be used in `asteval.Interpereter` """ if nested: name = '_' if top: name = '_main' if 'name' in kws: name = kws.pop('name') symtable = Group(name=name, Group=Group) else: symtable = {} symtable.update(BUILTINS_TABLE) symtable.update(LOCALFUNCS) symtable.update(kws) math_functions = dict(MATH_TABLE.items()) if use_numpy: math_functions.update(NUMPY_TABLE) if nested: symtable['math'] = Group(name='math', **math_functions) symtable['Group'] = Group symtable._searchgroups = ('math',) else: symtable.update(math_functions) symtable.update(**kws) return symtable class Procedure: """Procedure: user-defined function for asteval. This stores the parsed ast nodes as from the 'functiondef' ast node for later evaluation. """ def __init__(self, name, interp, doc=None, lineno=None, body=None, text=None, args=None, kwargs=None, vararg=None, varkws=None): """TODO: docstring in public method.""" self.__ininit__ = True self.name = name self.__name__ = self.name self.__asteval__ = interp self.__raise_exc__ = self.__asteval__.raise_exception self.__doc__ = doc self.__body__ = body self.__argnames__ = args self.__kwargs__ = kwargs self.__vararg__ = vararg self.__varkws__ = varkws self.lineno = lineno self.__text__ = text if text is None: self.__text__ = f'{self.__signature__()}\n' + ast.unparse(self.__body__) self.__ininit__ = False def __setattr__(self, attr, val): if not getattr(self, '__ininit__', True): self.__raise_exc__(None, exc=TypeError, msg="procedure is read-only") self.__dict__[attr] = val def __dir__(self): return ['__getdoc__', 'argnames', 'kwargs', 'name', 'vararg', 'varkws'] def __getdoc__(self): doc = self.__doc__ if isinstance(doc, ast.Constant): doc = doc.value return doc def __repr__(self): """TODO: docstring in magic method.""" sig = self.__signature__() rep = f"" doc = self.__getdoc__() if doc is not None: rep = f"{rep}\n {doc}" return rep def __signature__(self): "call signature" sig = "" if len(self.__argnames__) > 0: sig = sig + ', '.join(self.__argnames__) if self.__vararg__ is not None: sig = sig + f"*{self.__vararg__}" if len(self.__kwargs__) > 0: if len(sig) > 0: sig = f"{sig}, " _kw = [f"{k}={v}" for k, v in self.__kwargs__] sig = f"{sig}{', '.join(_kw)}" if self.__varkws__ is not None: sig = f"{sig}, **{self.__varkws__}" return f"{self.name}({sig})" def __call__(self, *args, **kwargs): """TODO: docstring in public method.""" topsym = self.__asteval__.symtable if self.__asteval__.config.get('nested_symtable', False): sargs = {'_main': topsym} sgroups = topsym.get('_searchgroups', None) if sgroups is not None: for sxname in sgroups: sargs[sxname] = topsym.get(sxname) symlocals = Group(name=f'symtable_{self.name}_', **sargs) symlocals._searchgroups = list(sargs.keys()) else: symlocals = {} args = list(args) nargs = len(args) nkws = len(kwargs) nargs_expected = len(self.__argnames__) # check for too few arguments, but the correct keyword given if (nargs < nargs_expected) and nkws > 0: for name in self.__argnames__[nargs:]: if name in kwargs: args.append(kwargs.pop(name)) nargs = len(args) nargs_expected = len(self.__argnames__) nkws = len(kwargs) if nargs < nargs_expected: msg = f"{self.name}() takes at least" msg = f"{msg} {nargs_expected} arguments, got {nargs}" self.__raise_exc__(None, exc=TypeError, msg=msg) # check for multiple values for named argument if len(self.__argnames__) > 0 and kwargs is not None: msg = "multiple values for keyword argument" for targ in self.__argnames__: if targ in kwargs: msg = f"{msg} '{targ}' in Procedure {self.name}" self.__raise_exc__(None, exc=TypeError, msg=msg, lineno=self.lineno) # check more args given than expected, varargs not given if nargs != nargs_expected: msg = None if nargs < nargs_expected: msg = f"not enough arguments for Procedure {self.name}()" msg = f"{msg} (expected {nargs_expected}, got {nargs}" self.__raise_exc__(None, exc=TypeError, msg=msg) if nargs > nargs_expected and self.__vararg__ is None: if nargs - nargs_expected > len(self.__kwargs__): msg = f"too many arguments for {self.name}() expected at most" msg = f"{msg} {len(self.__kwargs__)+nargs_expected}, got {nargs}" self.__raise_exc__(None, exc=TypeError, msg=msg) for i, xarg in enumerate(args[nargs_expected:]): kw_name = self.__kwargs__[i][0] if kw_name not in kwargs: kwargs[kw_name] = xarg for argname in self.__argnames__: symlocals[argname] = args.pop(0) try: if self.__vararg__ is not None: symlocals[self.__vararg__] = tuple(args) for key, val in self.__kwargs__: if key in kwargs: val = kwargs.pop(key) symlocals[key] = val if self.__varkws__ is not None: symlocals[self.__varkws__] = kwargs elif len(kwargs) > 0: msg = f"extra keyword arguments for Procedure {self.name}: " msg = msg + ','.join(list(kwargs.keys())) self.__raise_exc__(None, msg=msg, exc=TypeError, lineno=self.lineno) except (ValueError, LookupError, TypeError, NameError, AttributeError): msg = f"incorrect arguments for Procedure {self.name}" self.__raise_exc__(None, msg=msg, lineno=self.lineno) if self.__asteval__.config.get('nested_symtable', False): save_symtable = self.__asteval__.symtable self.__asteval__.symtable = symlocals else: save_symtable = self.__asteval__.symtable.copy() self.__asteval__.symtable.update(symlocals) self.__asteval__.retval = None self.__asteval__._calldepth += 1 retval = None # evaluate script of function self.__asteval__.code_text.append(self.__text__) for node in self.__body__: self.__asteval__.run(node, lineno=node.lineno) if len(self.__asteval__.error) > 0: break if self.__asteval__.retval is not None: retval = self.__asteval__.retval self.__asteval__.retval = None if retval is ReturnedNone: retval = None break self.__asteval__.symtable = save_symtable self.__asteval__.code_text.pop() self.__asteval__._calldepth -= 1 symlocals = None return retval lmfit-asteval-40c3196/doc/000077500000000000000000000000001474326165400153165ustar00rootroot00000000000000lmfit-asteval-40c3196/doc/Makefile000066400000000000000000000033051474326165400167570ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = letter BUILDDIR = _build # Internal variables. ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(SPHINXOPTS) . .PHONY: html pdf all help clean dirhtml latex all: html pdf $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html cd $(BUILDDIR)/latex && make all-pdf cp -pr $(BUILDDIR)/latex/asteval.pdf $(BUILDDIR)/html/asteval.pdf @echo -cd $(BUILDDIR) && ln -s html asteval_doc && zip -pur asteval_doc.zip asteval_doc/* && mv asteval_doc.zip html && rm -f asteval_doc @echo "Build finished. The HTML pages are in _build/html." html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." tarball: all cd $(BUILDDIR)/html && tar cvzf ../../../_doc.tgz * cd ../../ @echo pdf: latex cd $(BUILDDIR)/latex && make all-pdf cp -pr $(BUILDDIR)/latex/asteval.pdf ./asteval.pdf help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " pdf pdf from latex version" @echo " all html, pdf, and doc.zip" @echo " clean to remove all output" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo @echo "Build finished; the LaTeX files are in _build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo "Running LaTeX files through pdflatex..." make -C _build/latex all-pdf @echo "pdflatex finished; the PDF files are in _build/latex." clean: -rm -rf _build/* lmfit-asteval-40c3196/doc/_static/000077500000000000000000000000001474326165400167445ustar00rootroot00000000000000lmfit-asteval-40c3196/doc/_static/empty000066400000000000000000000000001474326165400200130ustar00rootroot00000000000000lmfit-asteval-40c3196/doc/_templates/000077500000000000000000000000001474326165400174535ustar00rootroot00000000000000lmfit-asteval-40c3196/doc/_templates/indexsidebar.html000066400000000000000000000013221474326165400230000ustar00rootroot00000000000000

Contents

Get Asteval

Current version: {{ release }}

Install: pip install asteval

Develop:   github.com

Offline Documentation

PDF documentation
Zipped HTML and PDF


lmfit-asteval-40c3196/doc/api.rst000066400000000000000000000357261474326165400166360ustar00rootroot00000000000000.. _asteval_api: ======================== Asteval Reference ======================== .. _numpy: https://numpy.org .. module:: asteval The asteval module has a pretty simple interface, providing an :class:`Interpreter` class which creates an Interpreter of expressions and code. There are a few options available to control what language features to support, how to deal with writing to standard output and standard error, and specifying the symbol table. There are also a few convenience functions: :func:`valid_symbol_name` is useful for testing the validity of symbol names, and :func:`make_symbol_table` is useful for creating symbol tables that may be pre-loaded with custom symbols and functions. The :class:`Interpreter` class ========================================= .. autoclass:: Interpreter If not provided, a symbol table will be created with :func:`make_symbol_table` that will include several standard python builtin functions, several functions from the :py:mod:`math` module and (if available and not turned off) several functions from `numpy`_. The ``writer`` argument can be used to provide a place to send all output that would normally go to :py:data:`sys.stdout`. The default is, of course, to send output to :py:data:`sys.stdout`. Similarly, ``err_writer`` will be used for output that will otherwise be sent to :py:data:`sys.stderr`. The ``use_numpy`` argument can be used to control whether functions from `numpy`_ are loaded into the symbol table. Whether the user-code is able to overwrite the entries in the symbol table can be controlled with the ``readonly_symbols`` and ``builtins_readonly`` keywords. Configuring which features the Interpreter recognizes ======================================================== The interpreter can be configured to enable or disable many language constructs, named according to the AST node in the Python language definition. .. _node_table: **Table of optional Python AST nodes used asteval.** The minimal configuration excludes all of the nodes listed, to give a bare-bones mathematical language but will full support for Python data types and array slicing. +----------------+----------------------+-------------------+-------------------+ | node name | description | in default config | in minimal config | +================+======================+===================+===================+ | import | import statements | False | False | +----------------+----------------------+-------------------+-------------------+ | importfrom | from x import y | False | False | +----------------+----------------------+-------------------+-------------------+ | assert | assert statements | True | False | +----------------+----------------------+-------------------+-------------------+ | augassign | x += 1 | True | False | +----------------+----------------------+-------------------+-------------------+ | delete | delete statements | True | False | +----------------+----------------------+-------------------+-------------------+ | if | if/then blocks | True | False | +----------------+----------------------+-------------------+-------------------+ | ifexp | a = b if c else d | True | False | +----------------+----------------------+-------------------+-------------------+ | for | for loops | True | False | +----------------+----------------------+-------------------+-------------------+ | formattedvalue | f-strings | True | False | +----------------+----------------------+-------------------+-------------------+ | functiondef | define functions | True | False | +----------------+----------------------+-------------------+-------------------+ | print | print function | True | False | +----------------+----------------------+-------------------+-------------------+ | raise | raise statements | True | False | +----------------+----------------------+-------------------+-------------------+ | listcomp | list comprehension | True | False | +----------------+----------------------+-------------------+-------------------+ | dictcomp | dict comprehension | True | False | +----------------+----------------------+-------------------+-------------------+ | setcomp | set comprehension | True | False | +----------------+----------------------+-------------------+-------------------+ | try | try/except blocks | True | False | +----------------+----------------------+-------------------+-------------------+ | while | while blocks | True | False | +----------------+----------------------+-------------------+-------------------+ | with | with blocks | True | False | +----------------+----------------------+-------------------+-------------------+ The ``minimal`` configuration for the Interpreter will support many basic Python language constructs including all basic data types, operators, slicing. The ``default`` configuration adds many language constructs, including * if-elif-else conditionals * for loops, with ``else`` * while loops, with ``else`` * try-except-finally blocks * with blocks * augmented assignments: ``x += 1`` * if-expressions: ``x = a if TEST else b`` * list comprehension: ``out = [sqrt(i) for i in values]`` * set and dict comprehension, too. * print formatting with ``%``, ``str.format()``, or f-strings. * function definitions The nodes listed in Table :ref:`Table of optional Python AST nodes used asteval ` can be enabled and disabled individually with the appropriate ``no_NODE`` or ``with_NODE`` argument when creating the interpreter, or specifying a ``config`` dictionary. That is, you might construct an Interpreter as:: >>> from asteval import Interpreter >>> >>> aeval_nowhile = Interpreter(no_while=True) >>> >>> config = {'while': False, 'if': False, 'try': False, 'for': False, 'with': False} >>> aveal_noblocks = Interpreter(config=config) Passing, ``minimal=True`` will turn off all the nodes listed in Table :ref:`Table of optional Python AST nodes used asteval `:: >>> 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, 'listcomp': False, 'dictcomp': False, 'setcomp': False, 'try': False, 'while': False, 'with': False} As shown above, importing Python modules with ``import module`` or ``from module import method`` can be enabled, but is disabled by default. To enable these, use ``with_import=True`` and ``with_importfrom=True``, as :: >>> from asteval import Interpreter >>> aeval_max = Interpreter(with_import=True, with_importfrom=True) or by setting the config dictionary as described above: Interpreter methods and attributes ==================================== An Interpreter instance has many methods, but most of them are implementation details for how to handle particular AST nodes, and should not be considered as part of the usable API. The methods described below, and the examples elsewhere in this documentation should be used as the stable API. .. method:: eval(expression[, lineno=0[, show_errors=True[, raise_errors=False]]]) evaluate the expression, returning the result. :param expression: code to evaluate. :type expression: string :param lineno: line number (for error messages). :type lineno: int :param show_errors: whether to print error messages or leave them in the :attr:`errors` list. :type show_errors: bool :param raise_errors: whether to re-raise exceptions or leave them in the :attr:`errors` list. :type raise_errors: bool .. method:: __call__(expression[, lineno=0[, show_errors=True[, raise_errors=False]]]) same as :meth:`eval`. That is:: >>> from asteval import Interpreter >>> a = Interpreter() >>> a('x = 1') instead of:: >>> a.eval('x = 1') .. attribute:: symtable the symbol table where all data and functions for the Interpreter are stored and looked up. By default, this is a simple dictionary with symbol names as keys, and values of data and functions. If the ``nested_symtable`` option is used, the symbol tables will be a subclass of a dictionary with more features, as discussed in :ref:`symtable_section`. In either case, the symbol table can be accessed from the calling program using the :attr:`symtable` attribute of the Interpreter. This allows the calling program to read, insert, replace, or remove symbols to alter what symbols are known to your interpreter. .. attribute:: error a list of error information, filled on exceptions. You can test this after each call of the interpreter. It will be empty if the last execution was successful. If an error occurs, this will contain a liste of Exceptions raised. .. attribute:: error_msg the most recent error message. .. _symtable_section: Symbol Tables used in asteval ==================================== The symbol table holds all of the data used by the Interpreter. That is, when you execute ``a = b * cos(pi/3)``, the Interpreter sees that it needs to lookup values for ``b``, ``cos``, and ``pi`` (it already knows ``=``, ``*``, ``/``, ``(``, and ``)`` mean), and then set the value for ``a``. The place where it looks up and then sets those values for these assigned variables is the symbol table. Historically, and by default, the symbol table in Asteval is a simple dictionary with variable names as the keys, and their values as the corresponding values. This is slightly simpler than in Python or roughly equivalent to everything being "global". This isn't exactly true, and what happens inside an Asteval Procedure (basically, a function) is a little different as a special local symbol table (or Frame) is created for that function, but it is mostly true. Symbol names are limited to being valid Python object names, and must match ``[a-zA-Z_][a-zA-Z0-9_]*`` and not be a reserved word. The symbol table is held in the :attr:`symtable` attribute of the Interpreter, and can be accessed and manipulated from the containing Python program. This allows the calling program to read, insert, replace, or remove symbols to alter what symbols are known to your interpreter. That is, it is perfectly valid to do something like this:: >>> from asteval import Interpreter >>> aeval = Interpreter() >>> aeval.symtable['x'] = 10 >>> aeval('sqrt(x)') 3.1622776601683795 By default, the symbol table will be pre-loaded with many Python builtins, functions from the ``math`` module, and functions from ``numpy`` if available. You can control some of these settings or add symbols into the symbol table with the ``use_numpy`` and ``user_symbols`` arguments when creating an Interpreter. You can also build your own symbol table and pass that it, and use the ``readonly_symbols`` and ``builtins_readonly`` options to prevent some symbols to be writeable from within the Interpreter. You can also create your own symbol table, either as a plain dict, or with the :func:`make_symbol_table` function, and alter that to use as the ``symtable`` option when creating an Interpreter. That is, the calling program can fully control the symbol table, either pre-loading custom variables and functions or removing default functions. .. versionadded:: 0.9.31 New Style Symbol Table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Beginning with version 0.9.31, there is an option to use a more complex and nested symbol table. This symbol table uses a ``"Group"`` object which is a subclass of a Python dict that can also be used with ``object.attribute`` syntax:: >>> 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 As with the plain-dictionary symbol table, all symbols must be valid Python identifiers, and cannot be reserved words. In addition, this symbol table can be nested -- not flat -- and may have a special attribute called ``_searchgroups`` that give the name of sub-Groups to search for symbols. By default, when using this new-style symbol table, the mathematical functions imported from the ``math`` and ``numpy`` modules) are placed in a subgroup named ``math`` (with about 300 named functions and variables), and the ``_searchgroups`` variable is set to the tuple ``('math',)``. When looking for the a symbol in an expression like ``a = b * cos( pi /3)``, the Interpreter will have to find and use the symbols names for ``b``, ``cos`` and ``pi``. With the old-style symbol table, all of these must be in the flat dictionary, which makes it difficult to browse through the symbol table. With the new, nested symbol table, the names ``b``, ``cos`` and ``pi`` are first looked for in the top-level Group. If not found there, they are looked for in the subgroups named in ``_searchgroups``, in order and returned as soon as one is found. That is the expectation is that `b` would be found in the "top-level user Group", while ``cos`` and ``pi`` would be found in the ``math`` Group, and that:: >>> aeval('a = b * cos( pi /3)') >>> aeval('a = b * math.cos(math.pi /3)') would be equivalent, as if you had imported a module that would automatically be searched: something between ``import math`` and ``from math import *``. Though different from how Python works, if using Asteval as a domain-specific language, this nesting and automated searching can be quite useful. Utility Functions ==================== .. autofunction:: valid_symbol_name .. autofunction:: make_symbol_table To make and use a custom symbol table, one might do this:: 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)"))) which will print ``0.5``. lmfit-asteval-40c3196/doc/basics.rst000066400000000000000000000145221474326165400173200ustar00rootroot00000000000000================ Using Asteval ================ This chapter gives a quick overview of asteval, showing basic usage and the most important features. Further details can be found in the next chapter (:ref:`asteval_api`). Creating and using an asteval Interpreter ============================================= The asteval module is very easy to use. Import the module and create an Interpreter: >>> from asteval import Interpreter >>> aeval = Interpreter() and now you have an embedded interpreter for a procedural, mathematical language that is very much like python:: >>> aeval('x = sqrt(3)') >>> aeval('print(x)') 1.73205080757 >>> 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 There are lots of options when creating the Interpreter to controller what functionality is and isn't allowed and to pre-load data and functions. The default interpreter gives a limited but useful version of the Python language. accessing the symbol table ============================= The symbol table (that is, the mapping between variable and function names and the underlying objects) is a simple dictionary (by default, see :ref:`symtable_section` for details of an optional alternative) held in the :attr:`symtable` attribute of the interpreter, and can be read or written to:: >>> aeval('x = sqrt(3)') >>> aeval.symtable['x'] 1.73205080757 >>> aeval.symtable['y'] = 100 >>> aeval('print(y/8)') 12.5 Note here the use of true division even though the operands are integers. As with Python itself, valid symbol names must match the basic regular expression pattern:: valid_name = [a-zA-Z_][a-zA-Z0-9_]* In addition, certain names are reserved in Python, and cannot be used within the asteval interpreter. These reserved words are: and, as, assert, async, await, break, class, continue, def, del, elif, else, eval, except, exec, execfile, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, print, raise, return, try, while, with, True, False, None, __import__, __package__ built-in functions ======================= At startup, many symbols are loaded into the symbol table from Python's builtins and the ``math`` module. The builtins include several basic Python functions: abs, all, any, bin, bool, bytearray, bytes, chr, complex, dict, dir, divmod, enumerate, filter, float, format, frozenset, hash, hex, id, int, isinstance, len, list, map, max, min, oct, ord, pow, range, repr, reversed, round, set, slice, sorted, str, sum, tuple, zip and a large number of named exceptions: ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, DeprecationWarning, EOFError, EnvironmentError, Exception, False, FloatingPointError, GeneratorExit, IOError, ImportError, ImportWarning, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupError, MemoryError, NameError, None, NotImplemented, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, RuntimeWarning, StopIteration, SyntaxError, SyntaxWarning, SystemError, SystemExit, True, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, UnicodeWarning, ValueError, Warning, ZeroDivisionError The symbols imported from Python's ``math`` module include: acos, acosh, asin, asinh, atan, atan2, atanh, ceil, copysign, cos, cosh, degrees, e, exp, fabs, factorial, floor, fmod, frexp, fsum, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, pi, pow, radians, sin, sinh, sqrt, tan, tanh, trunc .. _numpy: https://numpy.org/ If available, about 300 additional symbols are imported from `numpy`_. conditionals and loops ========================== If-then-else blocks, for-loops (including the optional ``else`` block), ``while`` loops (also including optional ``else`` block), and ``with`` blocks are supported, and work exactly as they do in python. Thus: >>> code = """ sum = 0 for i in range(10): sum += i*sqrt(*1.0) if i % 4 == 0: sum = sum + 1 print("sum = ", sum) """ >>> aeval(code) sum = 114.049534067 comprehensions ================ list, dict, and set comprehension are supported, acting just as they do in Python. Generators, yield, and async programming are not currently supported. printing =============== For printing, asteval emulates Python's native :func:`print` function. You can change where output is sent with the ``writer`` argument when creating the interpreter, or suppress printing all together with the ``no_print`` option. By default, outputs are sent to :py:data:`sys.stdout`. writing functions =================== User-defined functions can be written and executed, as in python with a ``def`` block, for example:: >>> 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 exceptions =============== Asteval monitors and caches exceptions in the evaluated code. Brief error messages are printed (with Python's print function, and so using standard output by default), and the full set of exceptions is kept in the :attr:`error` attribute of the :class:`Interpreter` instance. This :attr:`error` attribute is a list of instances of the asteval :class:`ExceptionHolder` class, which is accessed through the :meth:`get_error` method. The :attr:`error` attribute is reset to an empty list at the beginning of each :meth:`eval`, so that errors are from only the most recent :meth:`eval`. Thus, to handle and re-raise exceptions from your Python code in a simple REPL loop, you'd want to do something similar to >>> 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) lmfit-asteval-40c3196/doc/conf.py000066400000000000000000000151661474326165400166260ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # asteval documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os from datetime import date # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx'] intersphinx_mapping = {'py': ('https://docs.python.org/3/', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'asteval' copyright = u'{}, Matthew Newville, The University of Chicago'.format(date.today().year) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import asteval release = asteval.__version__.split('+', 1)[0] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'bizstyle' # html_theme = 'nature' # html_theme = 'agogo' # html_theme_options = {'pagewidth':'85em', 'documentwidth':'60em', 'sidebarwidth': '25em', # # 'headercolor1': '#000080', # # 'headercolor2': '#0000A0', # } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None html_title = 'ASTEVAL: Minimal Python AST evaluator' # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = 'ASTEVAL: Minimal Python AST evaluator' # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = False # True # Custom sidebar templates, maps document names to template names. html_sidebars = {'index': ['indexsidebar.html','searchbox.html']} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'astevaldoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'asteval.tex', u'asteval documentation', u'Matthew Newville', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True lmfit-asteval-40c3196/doc/index.rst000066400000000000000000000073511474326165400171650ustar00rootroot00000000000000.. asteval documentation master file, ASTEVAL: Minimal Python AST Evaluator ================================================ .. _numpy: https://numpy.org/ .. _numpy_financial: https://numpy.org/numpy-financial/ The asteval package evaluates Python expressions and statements, providing a safer alternative to Python's builtin :py:func:`eval` and a richer, easier to use alternative to :py:func:`ast.literal_eval`. It does this by building an embedded interpreter for a subset of the Python language using Python's :py:mod:`ast` module. The emphasis and main area of application is the evaluation of mathematical expressions. Because of this emphasis, mathematical functions from Python's :py:mod:`math` module are built-in to asteval, and a large number of functions from `numpy`_ will be available if `numpy`_ is installed on your system. For backward compatibility, a few functions that were moved from `numpy`_ to `numpy_financial`_ will be imported, if that package is installed. While the primary goal is evaluation of mathematical expressions, many features and constructs of the Python language are supported by default. These features include array slicing and subscripting, if-then-else conditionals, while loops, for loops, try-except blocks, list comprehension, and user-defined functions. All objects in the asteval interpreter are truly Python objects, and all of the basic built-in data structures (strings, dictionaries, tuple, lists, sets, numpy arrays) are supported, including the built-in methods for these objects. However, asteval is by no means an attempt to reproduce Python with its own :py:mod:`ast` module. There are important differences and missing features compared to Python. Many of these absences are intentional, and part of the effort to try to make a safer version of :py:func:`eval`, while some are simply due to the reduced requirements for an embedded mini-language. These differences and absences include: 1. All variable and function symbol names are held in a single symbol table that can be accessed from the calling program. By default, this is a simple dictionary, giving a flat namespace. A more elaborate, still experimental, symbol table that allows both dictionary and attribute access can also be used. 2. creating classes is not allowed. 3. importing modules is not allowed, unless specifically enabled. 4. decorators, generators, type hints, and ``lambda`` are not supported. 5. ``yield``, ``await``, and async programming are not supported. 6. Many builtin functions (:py:func:`eval`, :py:func:`getattr`, :py:func:`hasattr`, :py:func:`setattr`, and :py:func:`delattr`) are not allowed. 7. Accessing many object attributes that can provide access to the python interpreter are not allowed. The resulting "asteval language" acts very much like miniature version of Python, focused on mathematical calculations, and with noticeable limitations. It is the kind of toy programming language you might use to introduce simple scientific programming concepts, but also includes much of the standard Python features to be a reasonably complete language and not too restricted from what someone familiar with Python would expect. Because asteval is designed for evaluating user-supplied input, safety against malicious or incompetent user input is an important concern. Asteval tries as hard as possible to prevent user-supplied input from crashing the Python interpreter or from returning exploitable parts of the Python interpreter. In this sense asteval is certainly safer than using :py:func:`eval`. However, asteval is an open source project written by volunteers, and we cannot guarantee that it is completely safe against malicious attacks. .. toctree:: :maxdepth: 2 installation basics api motivation lmfit-asteval-40c3196/doc/installation.rst000066400000000000000000000044361474326165400205600ustar00rootroot00000000000000==================================== Installing Asteval ==================================== .. _numpy: https://numpy.org/ .. _numpy_financial: https://numpy.org/numpy-financial/ .. _github: https://github.com/lmfit/asteval .. _PyPI: https://pypi.org/project/asteval/ Requirements ~~~~~~~~~~~~~~~ Asteval is a pure Python module. The latest stable version is |release|, which supports Python 3.9 through 3.13. Installing `asteval` requires `setuptools` and `setuptools_scm`. No other libraries outside of the standard library are required. If `numpy`_ and `numpy_financial`_ are available, `asteval` will make use of these libraries. Running the test suite requires the `pytest`, `coverage`, and `pytest-cov` modules, deployment uses `build` and `twine`, and building the documentation requires `sphinx`. Python 3.9 through 3.13 are tested on Windows, MacOS, and Linux, with and without `numpy`_ installed. Older Python versions have generally been supported by `asteval` until they are well past the end of security fixes. While `asteval` may continue to work with Python 3.8 or even 3.7, these are not supported. Support for new versions of the Python 3 series is not guaranteed until some time after the official release of that version, as we may not start testing until late in the "beta" period of development. Historically, the delay has not been too long, though `asteval` may not support newly introduced language features. Installing with `pip` ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The latest stable version of `asteval` is |release| and is available at `PyPI`_ or as a conda package. You should be able to install `asteval` with:: pip install asteval It may also be available on some conda channels, including `conda-forge`, but as it is a pure Python package with no dependencies or OS-specific extensions, using `pip` should be the preferred method on all platforms and environments. Development Version ~~~~~~~~~~~~~~~~~~~~~~~~ The latest development version can be found at the `github`_ repository, and cloned with:: git clone https://github.com/lmfit/asteval.git Installation from the source tree on any platform is can then be done with:: pip install . License ~~~~~~~~~~~~~ The `asteval` code and documentation is distribution under the following license: .. literalinclude:: ../LICENSE lmfit-asteval-40c3196/doc/motivation.rst000066400000000000000000000266661474326165400202610ustar00rootroot00000000000000.. _lmfit: https://github.com/lmfit/lmfit-py .. _xraylarch: https://github.com/xraypy/xraylarch ==================================== Motivation for Asteval ==================================== The asteval module allows you to evaluate a large subset of the Python language from within a python program, without using :py:func:`eval`. It is, in effect, a restricted version of Python's built-in :py:func:`eval`, forbidding several actions, and using (by default) a simple dictionary as a flat namespace. A completely fair question is: Why is this desirable? That is, why not simply use :py:func:`eval`, or just use Python itself? The short answer is that sometimes you want to allow evaluation of user input, or expose a simple or even scientific calculator inside a larger application. For this, :py:func:`eval` is pretty scary, as it exposes *all* of Python, which makes user input difficult to trust. Since asteval does not support the **import** statement (unless explicitly enabled) or many other constructs, user code cannot access the :py:mod:`os` and :py:mod:`sys` modules or any functions or classes outside those provided in the symbol table. Many of the other missing features (modules, classes, lambda, yield, generators) are similarly motivated by a desire for a safer version of :py:func:`eval`. The idea for asteval is to make a simple procedural, mathematically-oriented language that can be embedded into larger applications. In fact, the asteval module grew out the the need for a simple expression evaluator for scientific applications such as the `lmfit`_ and `xraylarch`_ modules. An early attempt using the `pyparsing` module worked but was error-prone and difficult to maintain. While the simplest of calculators or expressiona-evaluators is not hard with pyparsing, it turned out that using the Python :py:mod:`ast` module makes it much easier to implement a feature-rich scientific calculator, including slicing, complex numbers, keyword arguments to functions, etc. In fact, this approach meant that adding more complex programming constructs like conditionals, loops, exception handling, and even user-defined functions was fairly simple. An important benefit of using the :py:mod:`ast` module is that whole categories of implementation errors involving parsing, lexing, and defining a grammar disappear. Any valid python expression will be parsed correctly and converted into an Abstract Syntax Tree. Furthermore, the resulting AST is easy to walk through, greatly simplifying the evaluation process. What started as a desire for a simple expression evaluator grew into a quite useable procedural domain-specific language for mathematical applications. Asteval makes no claims about speed. Evaluating the AST involves many function calls, which is going to be slower than Python - often 4x slower than Python. That said, for certain use cases (see https://stackoverflow.com/questions/34106484), use of asteval and numpy can approach the speed of `eval` and the `numexpr` modules. How Safe is asteval? ======================= Asteval avoids all of the exploits we know about that make :py:func:`eval` dangerous. For reference, see, `Eval is really dangerous `_ and the comments and links therein. From this discussion it is apparent that not only is :py:func:`eval` unsafe, but that it is a difficult prospect to make any program that takes user input perfectly safe. In particular, if a user can cause Python to crash with a segmentation fault, safety cannot be guaranteed. Asteval explicitly forbids the exploits described in the above link, and works hard to prevent malicious code from crashing Python or accessing the underlying operating system. That said, we cannot guarantee that asteval is completely safe from malicious code. We claim only that it is safer than the builtin :py:func:`eval`, and that you might find it useful. We also note that several other Python libraries that evaluate user-supplied expressions, including `numexpr` and `sympy` use the builtin :py:func:`eval` as part of their processing. Some of the things not allowed in the asteval interpreter for safety reasons include: * importing modules. Neither ``import`` nor ``__import__`` are supported by default. If you do want to support ``import`` and ``import from``, you have to explicitly enable these. * create classes or modules. * use ``string.format()``, though f-string formatting and using the ``%`` operator for string formatting are supported. * access to Python's :py:func:`eval`, :py:func:`getattr`, :py:func:`hasattr`, :py:func:`setattr`, and :py:func:`delattr`. * accessing object attributes that begin and end with ``__``, the so-called ``dunder`` attributes. This will include (but is not limited to ``__globals__``, ``__code__``, ``__func__``, ``__self__``, ``__module__``, ``__dict__``, ``__class__``, ``__call__``, and ``__getattribute__``. None of these can be accessed for any object. In addition (and following the discussion in the link above), the following attributes are blacklisted for all objects, and cannot be accessed: ``func_globals``, ``func_code``, ``func_closure``, ``im_class``, ``im_func``, ``im_self``, ``gi_code``, ``gi_frame``, ``f_locals``, ``__mro__``, ``_mro`` [Note: this list may be incomplete - there may be other disallowed attributes]. While this approach of making a blacklist cannot be guaranteed to be complete, it does eliminate entire classes of attacks known to be able to seg-fault the Python interpreter or give access to the operating system. An important caveat is that a typical use of asteval will import and expose numpy ``ufuncs`` from the numpy module. Several of these can seg-fault Python without too much trouble. If you safety from user input causing segmentation fault is a primary concern, you may want to consider disabling the use of numpy, or take extra care to specify what numpy functions can be used. In 2024, an independent security audit of asteval done by Andrew Effenhauser, Ayman Hammad, and Daniel Crowley in the X-Force Security Research division of IBM showed insecurities with ``string.format``, so that access to this and ``string.format_map`` method were removed. In addition, this audit showed that the ``numpy`` submodules ``linalg``, ``fft``, and ``polynomial`` expose many exploitable objects, so these submodules were removed by default. If needed, these modules can be added to any Interpreter either using the ``user_symbols`` argument when creating it, or adding the needed symbols to the symbol table after the Interpreter is created. In 2025, William Khem Marquez demonstrated two vulnerabilities: one from leaving some AST objects exposed within the interpreter for user-defined functions ("Procedures"), and one with f-string formatting. Both of these were fixed for version 1.0.6. There are other categories of safety that asteval may attempt to address, but cannot guarantee success. The most important of these is resource hogging, which might be used for a denial-of-service attack. There is no guaranteed timeout on any calculation, and so a reasonable looking calculation such as:: from asteval import Interpreter aeval = Interpreter() txt = """ nmax = 1e8 a = sqrt(arange(nmax)) # using numpy.sqrt() and numpy.arange() """ aeval.eval(txt) can take a noticeable amount of CPU time - if it does not, increasing that value of ``nmax`` almost certainly will, and can even crash the Python shell. As another example, and an illustration of the fundamental problem, consider the Python expression ``a = x**y**z``. For values ``x=y=z=5``, the run time will be well under 0.001 seconds. For ``x=y=z=8``, run time will still be under 1 sec. Changing to ``x=8, y=9, z=9``, Python will ake several seconds (the value is :math:`\sim 10^{350,000,000}`) With ``x=y=z=9``, executing that statement may take more than 1 hour on some machines. It is not hard to come up with short program that would run for hundreds of years, which probably exceeds everyones threshold for an acceptable run-time. The point here is tha there simply is not a good way to predict how long any code will take to run from the text of the code itself: run time cannot be determined lexically. To be clear, for the ``x**y**z`` exponentiation example, asteval will raise a runtime error, telling you that an exponent > 10,000 is not allowed. Several other attempts are also made to prevent long-running operations or memory exhaustion. These checks will prevent: * statements longer than 50,000 bytes. * values of exponents (``p`` in ``x**p``) > 10,000. * string operations with strings longer than 262144 bytes * shift operations with shifts (``p`` in ``x << p``) > 1000. * more than 262144 open buffers * opening a file with a mode other than ``'r'``, ``'rb'``, or ``'ru'``. These checks happen at runtime, not by analyzing the text of the code. As with the example above using ``numpy.arange``, very large arrays and lists can be created that might approach memory limits. There are countless other "clever ways" to have very long run times that cannot be readily predicted from the text of the code. By default, the list of supported functions does include Python's ``open()`` -- in read-only mode -- which will allow disk access to the untrusted user. If ``numpy`` is supported, its ``load()`` and ``loadtxt()`` functions will also normally be supported. By itself, including these functions does not elevate permissions, and access is restricted to 'read-only mode'. Still, the user of the asteval interpreter would be able to read files with the privileges of the calling program. In some cases, this may not be desirable, and you may want to remove some of these functions from the symbol table, re-implement them, or ensure that your program cannot access information on disk that should be kept private. The exponential example also highlights the issue that there is not a good way to check for a long-running calculation within a single Python process. That calculation is not stuck within the Python interpreter, but in C code (no doubt the ``pow()`` function) called by the Python interpreter itself. That call will not return from the C library to the Python interpreter or allow other threads to run until that call is done. That means that from within a single process, there is not a reliable way to tell asteval (or really, even Python) when a calculation has taken too long: Denial of Service is hard to detect before it happens, and even challenging to detect while it is happening. The only reliable way to limit run time is at the level of the operating system, with a second process watching the execution time of the asteval process and either try to interrupt it or kill it. For a limited range of problems, you can try to avoid asteval taking too long. For example, you may try to limit the *recursion limit* when executing expressions, with a code like this:: import contextlib @contextlib.contextmanager def limited_recursion(recursion_limit): old_limit = sys.getrecursionlimit() sys.setrecursionlimit(recursion_limit) try: yield finally: sys.setrecursionlimit(old_limit) with limited_recursion(100): Interpreter().eval(...) In summary, while asteval attempts to be safe and is definitely safer than using :py:func:`eval`, there may be ways that using asteval could lead to increased risk of malicious use. Recommendations for how to improve this situation would be greatly appreciated. lmfit-asteval-40c3196/pyproject.toml000066400000000000000000000027561474326165400174770ustar00rootroot00000000000000[build-system] requires = ["setuptools>=45", "setuptools_scm>=6.2"] build-backend = "setuptools.build_meta" [tool.setuptools_scm] write_to = "asteval/version.py" version_scheme = "post-release" [tool.setuptools.packages.find] include = ["asteval"] [tool.coverage.run] omit = ["tests/*"] [tool.pytest.ini_options] addopts = "--cov=asteval --cov-report html" [project] name = "asteval" dynamic = ["version"] requires-python = ">= 3.9" description = "Safe, minimalistic evaluator of python expression using ast module" readme = "README.rst" authors = [ {name = "Matthew Newville", email = "matt.newville@gmail.com"} ] license = {file = "LICENSE"} keywords = ["AST", "expression evaluation", "eval"] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: PyPy", ] [project.urls] Homepage = " https://github.com/lmfit/asteval" Documentation = "https://lmfit.github.io/asteval/" Tracker = "https://github.com/lmfit/asteval/issues" [project.optional-dependencies] dev = ["build", "twine"] doc = ["Sphinx"] test = ["pytest", "pytest-cov", "coverage"] all = ["asteval[dev, doc, test]"] lmfit-asteval-40c3196/setup.py000066400000000000000000000001321474326165400162570ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup if __name__ == "__main__": setup() lmfit-asteval-40c3196/tests/000077500000000000000000000000001474326165400157135ustar00rootroot00000000000000lmfit-asteval-40c3196/tests/test_asteval.py000066400000000000000000001467531474326165400210030ustar00rootroot00000000000000#!/usr/bin/env python """ Base TestCase for asteval """ import ast import math import os import textwrap import time import unittest from functools import partial from io import StringIO from sys import version_info from tempfile import NamedTemporaryFile import pytest from asteval import Interpreter, NameFinder, make_symbol_table from asteval.astutils import get_ast_names HAS_NUMPY = False try: import numpy as np from numpy.testing import assert_allclose HAS_NUMPY = True except ImportError: HAS_NUMPY = False def make_interpreter(nested_symtable=True): interp = Interpreter(nested_symtable=nested_symtable) interp.writer = NamedTemporaryFile('w', delete=False, prefix='astevaltest') return interp def read_stdout(interp): stdout = interp.writer stdout.flush() stdout.close() time.sleep(0.1) fname = stdout.name with open(stdout.name) as inp: out = inp.read() interp.writer = NamedTemporaryFile('w', delete=False, prefix='astevaltest') os.unlink(fname) return out def isvalue(interp, sym, val): tval = interp.symtable.get(sym) if HAS_NUMPY and isinstance(tval, np.ndarray): assert_allclose(tval, val, rtol=0.01) else: assert tval == val def isnear(interp, expr, val): tval = interp(expr) if HAS_NUMPY: assert_allclose(tval, val, rtol=1.e-4, atol=1.e-4) def istrue(interp, expr): """assert that an expression evaluates to True""" val = interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return bool(val) def isfalse(interp, expr): """assert that an expression evaluates to False""" val = interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return not bool(val) def check_output(interp, chk_str, exact=False): out = read_stdout(interp).split('\n') if out: if exact: return chk_str == out[0] return chk_str in out[0] return False def check_error(interp, chk_type='', chk_msg=''): try: errtype, errmsg = interp.error[0].get_error() assert errtype == chk_type if chk_msg: assert chk_msg in errmsg except IndexError: if chk_type: assert False def test_py3(): assert version_info.major > 2 @pytest.mark.parametrize("nested", [False, True]) def test_dict_index(nested): """dictionary indexing""" interp = make_interpreter(nested_symtable=nested) interp("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") istrue(interp, "a_dict['a'] == 1") istrue(interp, "a_dict['d'] == 4") @pytest.mark.parametrize("nested", [False, True]) def test_dict_set_index(nested): """dictionary indexing""" interp = make_interpreter(nested_symtable=nested) interp("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") interp("a_dict['a'] = -4") interp("a_dict['e'] = 73") istrue(interp, "a_dict['a'] == -4") istrue(interp, "a_dict['e'] == 73") interp("b_dict = {}") interp("keyname = 'a'") interp("b_dict[keyname] = (1, -1, 'x')") istrue(interp, "b_dict[keyname] == (1, -1, 'x')") @pytest.mark.parametrize("nested", [False, True]) def test_list_index(nested): """list indexing""" interp = make_interpreter(nested_symtable=nested) interp("a_list = ['a', 'b', 'c', 'd', 'o']") istrue(interp, "a_list[0] == 'a'") istrue(interp, "a_list[1] == 'b'") istrue(interp, "a_list[2] == 'c'") @pytest.mark.parametrize("nested", [False, True]) def test_tuple_index(nested): """tuple indexing""" interp = make_interpreter(nested_symtable=nested) interp("a_tuple = (5, 'a', 'x')") istrue(interp, "a_tuple[0] == 5") istrue(interp, "a_tuple[2] == 'x'") @pytest.mark.parametrize("nested", [False, True]) def test_string_index(nested): """string indexing""" interp = make_interpreter(nested_symtable=nested) interp("a_string = 'hello world'") istrue(interp, "a_string[0] == 'h'") istrue(interp, "a_string[6] == 'w'") istrue(interp, "a_string[-1] == 'd'") istrue(interp, "a_string[-2] == 'l'") @pytest.mark.parametrize("nested", [False, True]) def test_sets(nested): """build, use set""" interp = make_interpreter(nested_symtable=nested) interp("a_set = {'a', 'b', 'c', 'd', 'c'}") istrue(interp, "len(a_set) == 4") istrue(interp, "'b' in a_set") interp("c_major7 = {'c', 'e', 'g', 'b'}") interp("d_minor7 = {'d', 'f', 'a', 'c'}") interp("e_minor7 = {'e', 'g', 'b', 'd'}") interp("f_major7 = {'f', 'a', 'c', 'e'}") interp("g_dom7 = {'g', 'b', 'd', 'f'}") interp("a_minor7 = {'a', 'c', 'e', 'g'}") interp("b_halfdim = {'b', 'd', 'f', 'a'}") interp("c_diatonic = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}") interp("phrase = d_minor7 + g_dom7 + c_major7") check_error(interp, 'TypeError') istrue(interp, "c_major7 & d_minor7 == {'c'}") istrue(interp, "c_major7 & e_minor7 == {'b', 'g', 'e'}") istrue(interp, "c_major7 | d_minor7 == c_diatonic") @pytest.mark.parametrize("nested", [False, True]) def test_basic(nested): """build, use set""" interp = make_interpreter(nested_symtable=nested) assert interp("4") == 4 v = interp("'x'") assert v == 'x' v = interp("b'x'") assert v == b'x' v = interp("str(4)") assert v == '4' v = interp("repr(4)") assert v == '4' assert interp("...") == ... assert not interp("False") interp("x = 8") interp("x.foo = 3") check_error(interp, 'AttributeError') interp("del x") @pytest.mark.parametrize("nested", [False, True]) def test_fstring(nested): "fstrings" interp = make_interpreter(nested_symtable=nested) interp("x = 2523.33/723") interp("s = f'{x:+.3f}'") istrue(interp, "s == '+3.490'") interp("chie = '\u03c7(E)'") interp("v_s = f'{chie!s}'") interp("v_r = f'{chie!r}'") interp("v_a = f'{chie!a}'") istrue(interp, "v_s == '\u03c7(E)'") istrue(interp, '''v_r == "'\u03c7(E)'"''') istrue(interp, '''v_a == "'\\\\u03c7(E)'"''') @pytest.mark.parametrize("nested", [False, True]) def test_verylong_strings(nested): "test that long string raises an error" interp = make_interpreter(nested_symtable=nested) longstr = "statement_of_somesize" * 5000 interp(longstr) check_error(interp, 'RuntimeError') @pytest.mark.parametrize("nested", [False, True]) def test_ndarray_index(nested): """nd array indexing""" interp = make_interpreter(nested_symtable=nested) if HAS_NUMPY: interp("a_ndarray = 5*arange(20)") assert interp("a_ndarray[2]") == 10 assert interp("a_ndarray[4]") == 20 @pytest.mark.parametrize("nested", [False, True]) def test_ndarrayslice(nested): """array slicing""" interp = make_interpreter(nested_symtable=nested) interp("xlist = lisr(range(12))") istrue(interp, "x[::3] == [0, 3, 6, 9]") if HAS_NUMPY: interp("a_ndarray = arange(200).reshape(10, 20)") istrue(interp, "a_ndarray[1:3,5:7] == array([[25,26], [45,46]])") interp("y = arange(20).reshape(4, 5)") istrue(interp, "y[:,3] == array([3, 8, 13, 18])") istrue(interp, "y[...,1] == array([1, 6, 11, 16])") istrue(interp, "y[1,:] == array([5, 6, 7, 8, 9])") interp("y[...,1] = array([2, 2, 2, 2])") istrue(interp, "y[1,:] == array([5, 2, 7, 8, 9])") interp("xarr = arange(12)") istrue(interp, "x[::3] == array([0, 3, 6, 9])") @pytest.mark.parametrize("nested", [False, True]) def test_while(nested): """while loops""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" n=0 while n < 8: n += 1 """)) isvalue(interp, 'n', 8) interp(textwrap.dedent(""" n=0 while n < 8: n += 1 if n > 3: break else: n = -1 """)) isvalue(interp, 'n', 4) interp(textwrap.dedent(""" n=0 while n < 8: n += 1 else: n = -1 """)) isvalue(interp, 'n', -1) interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) isvalue(interp, 'n', 10) isvalue(interp, 'i', 5) interp(textwrap.dedent(""" n=0 while n < 10: n += 1 print( ' n = ', n) if n > 5: break print( 'finish: n = ', n) """)) isvalue(interp, 'n', 6) @pytest.mark.parametrize("nested", [False, True]) def test_while_continue(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) isvalue(interp, 'n', 10) isvalue(interp, 'i', 5) @pytest.mark.parametrize("nested", [False, True]) def test_while_break(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" n = 0 while n < 10: n += 1 if n > 6: break print( 'finish: n = ', n) """)) isvalue(interp, 'n', 7) @pytest.mark.parametrize("nested", [False, True]) def test_with(nested): "test with" interp = make_interpreter(nested_symtable=nested) tmpfile = NamedTemporaryFile('w', delete=False, prefix='asteval_test') tmpfile.write('hello world\nline 2\nline 3\n\n') tmpfile.close() time.sleep(0.25) fname = tmpfile.name.replace('\\', '/') interp(textwrap.dedent(""" with open('{0}', 'r') as fh: lines = fh.readlines() """.format(fname))) lines = interp.symtable['lines'] fh1 = interp.symtable['fh'] assert fh1.closed assert len(lines) > 2 assert lines[1].startswith('line') @pytest.mark.parametrize("nested", [False, True]) def test_assert(nested): """test assert statements""" interp = make_interpreter(nested_symtable=nested) interp.error = [] interp('n=6') interp('assert n==6') check_error(interp, None) interp('assert n==7') check_error(interp, 'AssertionError') interp('assert n==7, "no match"') check_error(interp, 'AssertionError', 'no match') @pytest.mark.parametrize("nested", [False, True]) def test_for(nested): """for loops""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" n=0 for i in range(10): n += i """)) isvalue(interp, 'n', 45) interp(textwrap.dedent(""" n=0 for i in range(10): n += i else: n = -1 """)) isvalue(interp, 'n', -1) if HAS_NUMPY: interp(textwrap.dedent(""" n=0 for i in arange(10): n += i """)) isvalue(interp, 'n', 45) interp(textwrap.dedent(""" n=0 for i in arange(10): n += i else: n = -1 """)) isvalue(interp, 'n', -1) @pytest.mark.parametrize("nested", [False, True]) def test_for_break(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" n=0 for i in range(10): n += i if n > 2: break else: n = -1 """)) isvalue(interp, 'n', 3) if HAS_NUMPY: interp(textwrap.dedent(""" n=0 for i in arange(10): n += i if n > 2: break else: n = -1 """)) isvalue(interp, 'n', 3) @pytest.mark.parametrize("nested", [False, True]) def test_if(nested): """runtime errors test""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" zero = 0 if zero == 0: x = 1 if zero != 100: x = x+1 if zero > 2: x = x + 1 else: y = 33 """)) isvalue(interp, 'x', 2) isvalue(interp, 'y', 33) @pytest.mark.parametrize("nested", [False, True]) def test_print(nested): """print (ints, str, ....)""" interp = make_interpreter(nested_symtable=nested) interp("print(31)") check_output(interp, '31\n', True) interp("print('%s = %.3f' % ('a', 1.2012345))") check_output(interp, 'a = 1.201\n', True) interp("print('{0:s} = {1:.2f}'.format('a', 1.2012345))") check_output(interp, 'a = 1.20\n', True) @pytest.mark.parametrize("nested", [False, True]) def test_repr(nested): """repr of dict, list""" interp = make_interpreter(nested_symtable=nested) interp("x = {'a': 1, 'b': 2, 'c': 3}") interp("y = ['a', 'b', 'c']") interp("rep_x = repr(x['a'])") interp("rep_y = repr(y)") interp("rep_y , rep_x") interp("repr(None)") isvalue(interp, "rep_x", "1") isvalue(interp, "rep_y", "['a', 'b', 'c']") @pytest.mark.parametrize("nested", [False, True]) def test_cmp(nested): """numeric comparisons""" interp = make_interpreter(nested_symtable=nested) istrue(interp, "3 == 3") istrue(interp, "3.0 == 3") istrue(interp, "3.0 == 3.0") istrue(interp, "3 != 4") istrue(interp, "3.0 != 4") istrue(interp, "3 >= 1") istrue(interp, "3 >= 3") istrue(interp, "3 <= 3") istrue(interp, "3 <= 5") istrue(interp, "3 < 5") istrue(interp, "5 > 3") isfalse(interp, "3 == 4") isfalse(interp, "3 > 5") isfalse(interp, "5 < 3") @pytest.mark.parametrize("nested", [False, True]) def test_comparisons_return(nested): """test comparisons that do not return a bool""" interp = make_interpreter(nested_symtable=nested) if HAS_NUMPY: x = np.arange(10)/1.2 out = x > 2.3 interp("x = arange(10)/1.2") interp("out = x > 2.3") assert all(interp.symtable['out'] == out) assert interp.symtable['out'].sum() == 7 interp("out = (x > 2.3 < 6.2)") assert interp.error.pop().exc == ValueError @pytest.mark.parametrize("nested", [False, True]) def test_bool(nested): """boolean logic""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" yes = True no = False nottrue = False a = range(7)""")) istrue(interp, "yes") isfalse(interp, "no") isfalse(interp, "nottrue") isfalse(interp, "yes and no or nottrue") isfalse(interp, "yes and (no or nottrue)") isfalse(interp, "(yes and no) or nottrue") istrue(interp, "yes or no and nottrue") istrue(interp, "yes or (no and nottrue)") isfalse(interp, "(yes or no) and nottrue") istrue(interp, "yes or not no") istrue(interp, "(yes or no)") isfalse(interp, "not (yes or yes)") isfalse(interp, "not (yes or no)") isfalse(interp, "not (no or yes)") istrue(interp, "not no or yes") isfalse(interp, "not yes") istrue(interp, "not no") @pytest.mark.parametrize("nested", [False, True]) def test_bool_coerce(nested): """coercion to boolean""" interp = make_interpreter(nested_symtable=nested) istrue(interp, "1") isfalse(interp, "0") istrue(interp, "'1'") isfalse(interp, "''") istrue(interp, "[1]") isfalse(interp, "[]") istrue(interp, "(1)") istrue(interp, "(0,)") isfalse(interp, "()") istrue(interp, "dict(y=1)") isfalse(interp, "{}") @pytest.mark.parametrize("nested", [False, True]) def test_assignment(nested): """variables assignment""" interp = make_interpreter(nested_symtable=nested) interp('n = 5') isvalue(interp, "n", 5) interp('s1 = "a string"') isvalue(interp, "s1", "a string") interp('b = (1,2,3)') isvalue(interp, "b", (1, 2, 3)) if HAS_NUMPY: interp('a = 1.*arange(10)') isvalue(interp, "a", np.arange(10)) interp('a[1:5] = 1 + 0.5 * arange(4)') isnear(interp, "a", np.array([0., 1., 1.5, 2., 2.5, 5., 6., 7., 8., 9.])) @pytest.mark.parametrize("nested", [False, True]) def test_names(nested): """names test""" interp = make_interpreter(nested_symtable=nested) interp('nx = 1') interp('nx1 = 1') # use \u escape b/c python 2 complains about file encoding interp('\u03bb = 1') interp('\u03bb1 = 1') @pytest.mark.parametrize("nested", [False, True]) def test_syntaxerrors_1(nested): """assignment syntax errors test""" interp = make_interpreter(nested_symtable=nested) for expr in ('class = 1', 'for = 1', 'if = 1', 'raise = 1', '1x = 1', '1.x = 1', '1_x = 1', 'return 3', 'return False'): failed = False # noinspection PyBroadException try: interp(expr, show_errors=False, raise_errors=True) except: failed = True assert failed check_error(interp, 'SyntaxError') @pytest.mark.parametrize("nested", [False, True]) def test_unsupportednodes(nested): """unsupported nodes""" interp = make_interpreter(nested_symtable=nested) for expr in ('f = lambda x: x*x', 'yield 10'): failed = False # noinspection PyBroadException try: interp(expr, show_errors=False, raise_errors=True) except: failed = True assert failed check_error(interp, 'NotImplementedError') @pytest.mark.parametrize("nested", [False, True]) def test_syntaxerrors_2(nested): """syntax errors test""" interp = make_interpreter(nested_symtable=nested) for expr in ('x = (1/*)', 'x = 1.A', 'x = A.2'): failed = False # noinspection PyBroadException try: interp(expr, show_errors=False, raise_errors=True) except: # RuntimeError: failed = True assert failed check_error(interp, 'SyntaxError') @pytest.mark.parametrize("nested", [False, True]) def test_runtimeerrors_1(nested): """runtime errors test""" interp = make_interpreter(nested_symtable=nested) interp("zero = 0") interp("astr ='a string'") interp("atup = ('a', 'b', 11021)") interp("arr = range(20)") for expr, errname in (('x = 1/zero', 'ZeroDivisionError'), ('x = zero + nonexistent', 'NameError'), ('x = zero + astr', 'TypeError'), ('x = zero()', 'TypeError'), ('x = astr * atup', 'TypeError'), ('x = arr.shapx', 'AttributeError'), ('arr.shapx = 4', 'AttributeError'), ('del arr.shapx', 'KeyError'), ('x, y = atup', 'ValueError')): failed, errtype, errmsg = False, None, None # noinspection PyBroadException try: interp(expr, show_errors=False, raise_errors=True) except: failed = True assert failed check_error(interp, errname) @pytest.mark.parametrize("nested", [False, True]) def test_ndarrays(nested): """simple ndarrays""" if HAS_NUMPY: interp = make_interpreter(nested_symtable=nested) interp('n = array([11, 10, 9])') istrue(interp, "isinstance(n, ndarray)") istrue(interp, "len(n) == 3") isvalue(interp, "n", np.array([11, 10, 9])) interp('n = arange(20).reshape(5, 4)') istrue(interp, "isinstance(n, ndarray)") istrue(interp, "n.shape == (5, 4)") interp("myx = n.shape") interp("n.shape = (4, 5)") istrue(interp, "n.shape == (4, 5)") interp("a = arange(20)") interp("gg = a[1:13:3]") isvalue(interp, 'gg', np.array([1, 4, 7, 10])) interp("gg[:2] = array([0,2])") isvalue(interp, 'gg', np.array([0, 2, 7, 10])) interp('a, b, c, d = gg') isvalue(interp, 'c', 7) istrue(interp, '(a, b, d) == (0, 2, 10)') @pytest.mark.parametrize("nested", [False, True]) def test_binop(nested): """test binary ops""" interp = make_interpreter(nested_symtable=nested) interp('a = 10.0') interp('b = 6.0') istrue(interp, "a+b == 16.0") isnear(interp, "a-b", 4.0) istrue(interp, "a/(b-1) == 2.0") istrue(interp, "a*b == 60.0") @pytest.mark.parametrize("nested", [False, True]) def test_unaryop(nested): """test binary ops""" interp = make_interpreter(nested_symtable=nested) interp('a = -10.0') interp('b = -6.0') isnear(interp, "a", -10.0) isnear(interp, "b", -6.0) @pytest.mark.parametrize("nested", [False, True]) def test_del(nested): """test del function""" interp = make_interpreter(nested_symtable=nested) interp('a = -10.0') interp('b = -6.0') assert 'a' in interp.symtable assert 'b' in interp.symtable interp("del a") interp("del b") assert 'a' not in interp.symtable assert 'b' not in interp.symtable @pytest.mark.parametrize("nested", [False, True]) def test_math1(nested): """builtin math functions""" interp = make_interpreter(nested_symtable=nested) interp('n = sqrt(4)') istrue(interp, 'n == 2') isnear(interp, 'sin(pi/2)', 1) isnear(interp, 'cos(pi/2)', 0) istrue(interp, 'exp(0) == 1') if HAS_NUMPY: isnear(interp, 'exp(1)', np.e) @pytest.mark.parametrize("nested", [False, True]) def test_namefinder(nested): """test namefinder""" interp = make_interpreter(nested_symtable=nested) p = interp.parse('x+y+cos(z)') nf = NameFinder() nf.generic_visit(p) assert 'x' in nf.names assert 'y' in nf.names assert 'z' in nf.names assert 'cos' in nf.names @pytest.mark.parametrize("nested", [False, True]) def test_list_comprehension(nested): """test list comprehension""" interp = make_interpreter(nested_symtable=nested) interp('x = [i*i for i in range(4)]') isvalue(interp, 'x', [0, 1, 4, 9]) interp('x = [i*i for i in range(6) if i > 1]') isvalue(interp, 'x', [4, 9, 16, 25]) interp('x = [(i, j*2) for i in range(6) for j in range(2)]') isvalue(interp, 'x', [(0, 0), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2), (3, 0), (3, 2), (4, 0), (4, 2), (5, 0), (5, 2)]) interp.readonly_symbols = set('a') list_in = "x = [a*2 for a in range(5)]" interp(list_in) check_error(interp, 'NameError') @pytest.mark.parametrize("nested", [False, True]) def test_list_comprehension_more(nested): """more tests of list comprehension""" interp = make_interpreter(nested_symtable=nested) odd = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] interp('odd = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]') interp('even = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]') for expr in ['[2.5*x for x in range(4)]', '[(i, 5*i+j) for i in range(6) for j in range(3)]', '[(i, j*2) for i in range(6) for j in range(2) if i*j < 8]', '[(x, y) for (x,y) in [(1,2), (3,4)]]', '[(2*x, x+y) for (x,y) in [(1,3), (5,9)]]', '[p*2.5 for p in odd]', '[n for p in zip(odd, even) for n in p]', '[(i*i + 0.5) for i in range(4)]', '[i*3.2 for i in odd if i > 6 and i < 18]', '[i-1.0 for i in odd if i > 4 and i*2 not in (26, 34)]', ]: interp(f"out = {expr}") result = interp.symtable.get('out') assert repr(result) == repr(eval(expr)) @pytest.mark.parametrize("nested", [False, True]) def test_set_comprehension(nested): """test set comprehension""" interp = make_interpreter(nested_symtable=nested) set_in = "x = {(a,2*b) for a in range(5) for b in range(4)}" set_out = {(4, 0), (3, 4), (4, 6), (0, 2), (2, 2), (1, 0), (1, 6), (4, 2), (3, 0), (3, 6), (2, 4), (1, 2), (0, 4), (3, 2), (4, 4), (0, 0), (2, 0), (1, 4), (0, 6), (2, 6)} interp(set_in) isvalue(interp, "x", set_out) @pytest.mark.parametrize("nested", [False, True]) def test_dict_comprehension(nested): """test set comprehension""" interp = make_interpreter(nested_symtable=nested) dict_in = "x = {a:2*b for a in range(5) for b in range(4)}" dict_out = {0: 6, 1: 6, 2: 6, 3: 6, 4: 6} interp(dict_in) isvalue(interp, 'x', dict_out) dict_in = "x = {a:yield for a in range(5) for yield in range(4)}" interp(dict_in) check_error(interp, 'SyntaxError') @pytest.mark.parametrize("nested", [False, True]) def test_set_comprehension(nested): """test set comprehension""" interp = make_interpreter(nested_symtable=nested) set_in = "x = {(a,2*b) for a in range(5) for b in range(4)}" set_out = {(4, 0), (3, 4), (4, 6), (0, 2), (2, 2), (1, 0), (1, 6), (4, 2), (3, 0), (3, 6), (2, 4), (1, 2), (0, 4), (3, 2), (4, 4), (0, 0), (2, 0), (1, 4), (0, 6), (2, 6)} interp(set_in) isvalue(interp, "x", set_out) @pytest.mark.parametrize("nested", [False, True]) def test_dict_comprehension(nested): """test set comprehension""" interp = make_interpreter(nested_symtable=nested) dict_in = "x = {a:2*b for a in range(5) for b in range(4)}" dict_out = {0: 6, 1: 6, 2: 6, 3: 6, 4: 6} interp(dict_in) isvalue(interp, 'x', dict_out) dict_in = "x = {a:yield for a in range(5) for yield in range(4)}" interp(dict_in) check_error(interp, 'SyntaxError') @pytest.mark.parametrize("nested", [False, True]) def test_ifexp(nested): """test if expressions""" interp = make_interpreter(nested_symtable=nested) interp('x = 2') interp('y = 4 if x > 0 else -1') interp('z = 4 if x > 3 else -1') isvalue(interp, 'y', 4) isvalue(interp, 'z', -1) @pytest.mark.parametrize("nested", [False, True]) def test_ifexp(nested): """test if expressions""" interp = make_interpreter(nested_symtable=nested) interp('x = 2') interp('y = 4 if x > 0 else -1') interp('z = 4 if x > 3 else -1') isvalue(interp, 'y', 4) isvalue(interp, 'z', -1) @pytest.mark.parametrize("nested", [False, True]) def test_index_assignment(nested): """test indexing / subscripting on assignment""" if HAS_NUMPY: interp = make_interpreter(nested_symtable=nested) interp('x = arange(10)') interp('l = [1,2,3,4,5]') interp('l[0] = 0') interp('l[3] = -1') isvalue(interp, 'l', [0, 2, 3, -1, 5]) interp('l[0:2] = [-1, -2]') isvalue(interp, 'l', [-1, -2, 3, -1, 5]) interp('x[1] = 99') isvalue(interp, 'x', np.array([0, 99, 2, 3, 4, 5, 6, 7, 8, 9])) interp('x[0:2] = [9,-9]') isvalue(interp, 'x', np.array([9, -9, 2, 3, 4, 5, 6, 7, 8, 9])) @pytest.mark.parametrize("nested", [False, True]) def test_reservedwords(nested): """test reserved words""" interp = make_interpreter(nested_symtable=nested) for w in ('and', 'as', 'while', 'raise', 'else', 'class', 'del', 'def', 'import', 'None'): interp.error = [] # noinspection PyBroadException try: interp("%s= 2" % w, show_errors=False, raise_errors=True) except: pass check_error(interp, 'SyntaxError') for w in ('True', 'False'): interp.error = [] interp("%s= 2" % w) check_error(interp, 'SyntaxError') for w in ('eval', '__import__'): interp.error = [] interp("%s= 2" % w) check_error(interp, 'NameError') @pytest.mark.parametrize("nested", [False, True]) def test_raise(nested): """test raise""" interp = make_interpreter(nested_symtable=nested) interp("raise NameError('bob')") check_error(interp, 'NameError', 'bob') @pytest.mark.parametrize("nested", [False, True]) def test_tryexcept(nested): """test try/except""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" x = 5 try: x = x/0 except ZeroDivisionError: print( 'Error Seen!') x = -999 """)) isvalue(interp, 'x', -999) interp(textwrap.dedent(""" x = -1 try: x = x/0 except ZeroDivisionError: pass """)) isvalue(interp, 'x', -1) interp(textwrap.dedent(""" x = 15 try: raise Exception() x = 20 except: pass """)) isvalue(interp, 'x', 15) @pytest.mark.parametrize("nested", [False, True]) def test_tryelsefinally(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" def dotry(x, y): out, ok, clean = 0, False, False try: out = x/y except ZeroDivisionError: out = -1 else: ok = True finally: clean = True return out, ok, clean """)) interp("val, ok, clean = dotry(1, 2.0)") interp("print(ok, clean)") isnear(interp, "val", 0.5) isvalue(interp, "ok", True) isvalue(interp, "clean", True) interp("val, ok, clean = dotry(1, 0.0)") isvalue(interp, "val", -1) isvalue(interp, "ok", False) isvalue(interp, "clean", True) @pytest.mark.parametrize("nested", [False, True]) def test_function1(nested): """test function definition and running""" interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" def fcn(x, scale=2): 'test function' out = sqrt(x) if scale > 1: out = out * scale return out """)) interp("a = fcn(4, scale=9)") isvalue(interp, "a", 18) interp("a = fcn(9, scale=0)") isvalue(interp, "a", 3) interp("print(fcn)") check_output(interp, ' 5: return 1 return -1 def b(): return 2.5 def c(x=10): x = a(x=x) y = b() return x + y """ interp(textwrap.dedent(setup)) interp("o1 = c()") interp("o2 = c(x=0)") isvalue(interp, 'o1', 3.5) isvalue(interp, 'o2', 1.5) @pytest.mark.parametrize("nested", [False, True]) def test_astdump(nested): """test ast parsing and dumping""" interp = make_interpreter(nested_symtable=nested) astnode = interp.parse('x = 1') assert isinstance(astnode, ast.Module) assert isinstance(astnode.body[0], ast.Assign) assert isinstance(astnode.body[0].targets[0], ast.Name) assert isinstance(astnode.body[0].value, ast.Constant) assert astnode.body[0].targets[0].id == 'x' assert astnode.body[0].value.value == 1 dumped = interp.dump(astnode.body[0]) assert dumped.startswith('Assign') @pytest.mark.parametrize("nested", [False, True]) def test_get_ast_names(nested): """test ast_names""" interp = make_interpreter(nested_symtable=nested) interp('x = 12') interp('y = 9.9') astnode = interp.parse('z = x + y/3') names = get_ast_names(astnode) assert 'x' in names assert 'y' in names assert 'z' in names @pytest.mark.parametrize("nested", [False, True]) def test_safe_funcs(nested): interp = make_interpreter(nested_symtable=nested) interp("'*'*(2<<17)") check_error(interp, None) interp("'*'*(1+2<<17)") check_error(interp, 'RuntimeError') interp("'*'*(2<<17) + '*'") check_error(interp, 'RuntimeError') interp("1.01**10000") check_error(interp, None) interp("1.01**10001") check_error(interp, 'RuntimeError') interp("1.5**10000") check_error(interp, 'OverflowError') interp("1<<1000") check_error(interp, None) interp("1<<1001") check_error(interp, 'RuntimeError') @pytest.mark.parametrize("nested", [False, True]) def test_safe__numpyfuncs(nested): if HAS_NUMPY: interp = make_interpreter(nested_symtable=nested) interp("arg = linspace(0, 20000, 21)") interp("a = 3**arg") check_error(interp, 'RuntimeError') interp("a = 100 << arg") check_error(interp, 'RuntimeError') @pytest.mark.parametrize("nested", [False, True]) def test_safe_open(nested): interp = make_interpreter(nested_symtable=nested) interp('open("foo1", "wb")') check_error(interp, 'RuntimeError') interp('open("foo2", "rb")') check_error(interp, 'FileNotFoundError') interp('open("foo3", "rb", 2<<18)') check_error(interp, 'RuntimeError') @pytest.mark.parametrize("nested", [False, True]) def test_recursionlimit(nested): interp = make_interpreter(nested_symtable=nested) interp("""def foo(): return foo()\nfoo()""") check_error(interp, 'RecursionError') @pytest.mark.parametrize("nested", [False, True]) def test_kaboom(nested): """ test Ned Batchelder's 'Eval really is dangerous' - Kaboom test (and related tests)""" interp = make_interpreter(nested_symtable=nested) interp("""(lambda fc=(lambda n: [c for c in ().__class__.__bases__[0].__subclasses__() if c.__name__ == n][0]): fc("function")(fc("code")(0,0,0,0,"KABOOM",(),(),(),"","",0,""),{})() )()""") check_error(interp, 'NotImplementedError') # Safe, lambda is not supported interp("""[print(c) for c in ().__class__.__bases__[0].__subclasses__()]""") # Try a portion of the kaboom... check_error(interp, 'AttributeError', '__class__') # Safe, unsafe dunders are not supported interp("9**9**9**9**9**9**9**9") check_error(interp, 'RuntimeError') # Safe, safe_pow() catches this s = 'x = ' + '('*100 + '1' + ')'*100 interp(s) if version_info.minor > 8: isvalue(interp, 'x', 1) check_error(interp, None) else: check_error(interp, 'RuntimeError') # Hmmm, this is caught, but its still concerning... interp("compile('xxx')") check_error(interp, 'NameError') # Safe, compile() is not supported @pytest.mark.parametrize("nested", [False, True]) def test_exit_value(nested): """test expression eval - last exp. is returned by interpreter""" interp = make_interpreter(nested_symtable=nested) z = interp("True") assert z z = interp("x = 1\ny = 2\ny == x + x\n") assert z z = interp("x = 42\nx") assert z == 42 isvalue(interp, 'x', 42) z = interp("""def foo(): return 42\nfoo()""") assert z == 42 @pytest.mark.parametrize("nested", [False, True]) def test_interpreter_run(nested): interp = make_interpreter(nested_symtable=nested) interp('a = 12') interp.run('b = a + 2') isvalue(interp, 'b', 14) node = interp.parse('c = b - 7') interp.eval(node) isvalue(interp, 'c', 7) @pytest.mark.parametrize("nested", [False, True]) def test_removenodehandler(nested): interp = make_interpreter(nested_symtable=nested) handler = interp.remove_nodehandler('ifexp') interp('testval = 300') interp('bogus = 3 if testval > 100 else 1') check_error(interp, 'NotImplementedError') interp.set_nodehandler('ifexp', handler) interp('bogus = 3 if testval > 100 else 1') isvalue(interp, 'bogus', 3) @pytest.mark.parametrize("nested", [False, True]) def test_set_default_nodehandler(nested): interp = make_interpreter(nested_symtable=nested) handler_import = interp.set_nodehandler('import') handler_importfrom = interp.set_nodehandler('importfrom') interp('import ast') check_error(interp, None) interp('import notavailable') check_error(interp, 'ImportError') interp('from time import ctime, strftime') check_error(interp, None) interp('from time import ctime as tclock, strftime as s') check_error(interp, None) interp('import ast as pyast') check_error(interp, None) interp('x = pyast.parse("a = 1.0 + 3.4")') check_error(interp, None) interp.remove_nodehandler('import') interp.remove_nodehandler('importfrom') interp('from time import ctime') check_error(interp, 'NotImplementedError') @pytest.mark.parametrize("nested", [False, True]) def test_interpreter_opts(nested): i1 = Interpreter(no_ifexp=True, nested_symtable=nested) assert i1.node_handlers['ifexp'] == i1.unimplemented i1('y = 4 if x > 0 else -1') errtype, errmsg = i1.error[0].get_error() assert errtype == 'NotImplementedError' conf = {k: v for k, v in i1.config.items()} conf['ifexp'] = True imin = Interpreter(minimal=True, nested_symtable=nested) assert not imin.config['ifexp'] assert not imin.config['importfrom'] assert not imin.config['augassign'] assert not imin.config['with'] ix = Interpreter(with_import=True, with_importfrom=True, nested_symtable=nested) assert ix.node_handlers['ifexp'] != ix.unimplemented assert ix.node_handlers['import'] != ix.unimplemented assert ix.node_handlers['importfrom'] != ix.unimplemented i2 = Interpreter(config=conf, nested_symtable=nested) assert i2.node_handlers['ifexp'] != i2.unimplemented assert i2.node_handlers['import'] == i2.unimplemented @pytest.mark.parametrize("nested", [False, True]) def test_get_user_symbols(nested): interp = make_interpreter(nested_symtable=nested) interp("x = 1.1\ny = 2.5\nz = 788\n") usersyms = interp.user_defined_symbols() assert 'x' in usersyms assert 'y' in usersyms assert 'z' in usersyms assert 'foo' not in usersyms @pytest.mark.parametrize("nested", [False, True]) def test_custom_symtable(nested): "test making and using a custom symbol table" if HAS_NUMPY: 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)) sym_table = make_symbol_table(cosd=cosd, sind=sind, tand=tand, nested=nested, name='mysymtable') aeval = Interpreter(symtable=sym_table) aeval("x1 = sind(30)") aeval("x2 = cosd(30)") aeval("x3 = tand(45)") x1 = aeval.symtable['x1'] x2 = aeval.symtable['x2'] x3 = aeval.symtable['x3'] assert_allclose(x1, 0.50, rtol=0.001) assert_allclose(x2, 0.866025, rtol=0.001) assert_allclose(x3, 1.00, rtol=0.001) repr1 = repr(sym_table) if nested: repr2 = sym_table._repr_html_() assert 'Group' in repr1 assert 'Group' in repr2 else: assert isinstance(repr1, str) @pytest.mark.parametrize("nested", [False, True]) def test_numpy_renames_in_custom_symtable(nested): """test that numpy renamed functions are in symtable""" if HAS_NUMPY: sym_table = make_symbol_table(nested=nested) lnfunc = sym_table.get('ln', None) assert lnfunc is not None @pytest.mark.parametrize("nested", [False, True]) def test_readonly_symbols(nested): def foo(): return 31 usersyms = { "a": 10, "b": 11, "c": 12, "d": 13, "foo": foo, "bar": foo, "x": 5, "y": 7 } aeval = Interpreter(usersyms=usersyms, nested_symtable=nested, readonly_symbols={"a", "b", "c", "d", "foo", "bar"}) aeval("a = 20") aeval("def b(): return 100") aeval("c += 1") aeval("del d") aeval("def foo(): return 55") aeval("bar = None") aeval("x = 21") aeval("y += a") assert aeval("a") == 10 assert aeval("b") == 11 assert aeval("c") == 12 assert aeval("d") == 13 assert aeval("foo()") == 31 assert aeval("bar()") == 31 assert aeval("x") == 21 assert aeval("y") == 17 assert aeval("abs(8)") == 8 assert aeval("abs(-8)") == 8 aeval("def abs(x): return x*2") assert aeval("abs(8)") == 16 assert aeval("abs(-8)") == -16 aeval2 = Interpreter(builtins_readonly=True) assert aeval2("abs(8)") == 8 assert aeval2("abs(-8)") == 8 aeval2("def abs(x): return x*2") assert aeval2("abs(8)") == 8 assert aeval2("abs(-8)") == 8 @pytest.mark.parametrize("nested", [False, True]) def test_chained_compparisons(nested): interp = make_interpreter(nested_symtable=nested) interp('a = 7') interp('b = 12') interp('c = 19') interp('d = 30') assert interp('a < b < c < d') assert not interp('a < b < c/88 < d') assert not interp('a < b < c < d/2') @pytest.mark.parametrize("nested", [False, True]) def test_array_compparisons(nested): if HAS_NUMPY: interp = make_interpreter(nested_symtable=nested) interp("sarr = arange(8)") sarr = np.arange(8) ox1 = interp("sarr < 4.3") assert np.all(ox1 == (sarr < 4.3)) ox1 = interp("sarr == 4") assert np.all(ox1 == (sarr == 4)) @pytest.mark.parametrize("nested", [False, True]) def test_minimal(nested): aeval = Interpreter(builtins_readonly=True, minimal=True) aeval("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") assert aeval("a_dict['a'] == 1") assert aeval("a_dict['c'] == 3") @pytest.mark.parametrize("nested", [False, True]) def test_partial_exception(nested): sym_table = make_symbol_table(sqrt=partial(math.sqrt), nested=nested) aeval = Interpreter(symtable=sym_table) assert aeval("sqrt(4)") == 2 # Calling sqrt(-1) should raise a ValueError. When the interpreter # encounters an exception, it attempts to form an error string that # uses the function's __name__ attribute. Partials don't have a # __name__ attribute, so we want to make sure that an AttributeError is # not raised. result = aeval("sqrt(-1)") assert aeval.error.pop().exc == ValueError @pytest.mark.parametrize("nested", [False, True]) def test_inner_return(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" def func(): loop_cnt = 0 for i in range(5): for k in range(5): loop_cnt += 1 return (i, k, loop_cnt) """)) out = interp("func()") assert out == (0, 4, 5) @pytest.mark.parametrize("nested", [False, True]) def test_nested_break(nested): interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" def func_w(): for k in range(5): if k == 4: break something = 100 return k """)) assert 4 == interp("func_w()") @pytest.mark.parametrize("nested", [False, True]) def test_pow(nested): interp = make_interpreter(nested_symtable=nested) assert 2**-2 == interp("2**-2") @pytest.mark.parametrize("nested", [False, True]) def test_stringio(nested): """ test using stringio for output/errors """ interp = make_interpreter(nested_symtable=nested) out = StringIO() err = StringIO() intrep = Interpreter(writer=out, err_writer=err) intrep("print('out')") assert out.getvalue() == 'out\n' @pytest.mark.parametrize("nested", [False, True]) def test_gh129(nested): """ test that errors are propagated correctly, GH #129 """ interp = make_interpreter(nested_symtable=nested) interp('one, two, default = 1, 2, 3') interp(textwrap.dedent(""" try: output = some_var except NameError: output = None foo = output or default """)) assert len(interp.error) == 0 assert interp('foo') == 3 @pytest.mark.parametrize("nested", [False, True]) def test_no_duplicate_exception(nested): """ test that errors are not repeated GH #132 """ interp = make_interpreter(nested_symtable=nested) interp.run("print(hi)", with_raise=False) assert len(interp.error) == 1 assert interp.error[0].exc == NameError # with plain eval too interp.error = [] interp("print(hi)", raise_errors=False) assert len(interp.error) == 1 assert interp.error[0].exc == NameError @pytest.mark.parametrize("nested", [False, True]) def test_raise_errors_unknown_symbol(nested): """ test that raise_error raises corret error type. GH #133 """ interp = make_interpreter(nested_symtable=nested) interp.error = [] try: saw_exception = False interp.run("unknown_value", with_raise=True) except NameError: saw_exception = True assert saw_exception assert len(interp.error) == 1 assert interp.error[0].exc == NameError @pytest.mark.parametrize("nested", [False, True]) def test_delete_slice(nested): """ test that a slice can be deleted""" interp = make_interpreter(nested_symtable=nested) interp.run("dlist = [1,3,5,7,9,11,13,15,17,19,21]") interp.run("del dlist[4:7]") assert interp("dlist") == [1, 3, 5, 7, 15, 17, 19, 21] if nested: interp.run("g = Group()") interp.run("g.dlist = [1,3,5,7,9,11,13,15,17,19,21]") interp.run("del g.dlist[4:7]") assert interp("g.dlist") == [1, 3, 5, 7, 15, 17, 19, 21] @pytest.mark.parametrize("nested", [False, True]) def test_unsafe_procedure_access(nested): """ addressing https://github.com/lmfit/asteval/security/advisories/GHSA-vp47-9734-prjw """ interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" def my_func(x, y): return x+y my_func.__body__[0] = 'something else' """), raise_errors=False) error = interp.error[0] etype, fullmsg = error.get_error() assert 'no safe attribute' in error.msg assert etype == 'AttributeError' @pytest.mark.parametrize("nested", [False, True]) def test_unsafe_format_string_access(nested): """ addressing https://github.com/lmfit/asteval/security/advisories/GHSA-3wwr-3g9f-9gc7 """ interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" f"{dict:'\\x7B__fstring__.__class__.s\\x7D'}" """), raise_errors=False) error = interp.error[0] etype, fullmsg = error.get_error() assert 'no safe attribute' in error.msg assert etype == 'AttributeError' @pytest.mark.parametrize("nested", [False, True]) def test_unsafe_attr_dtypes(nested): """ addressing https://github.com/lmfit/asteval/security/advisories/GHSA-3wwr-3g9f-9gc7 """ interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" '{0}'.format(dict) """), raise_errors=False) error = interp.error[0] etype, fullmsg = error.get_error() assert 'no safe attribute' in error.msg assert etype == 'AttributeError' interp = make_interpreter(nested_symtable=nested) interp(textwrap.dedent(""" str.format('{0}', dict) """), raise_errors=False) error = interp.error[0] etype, fullmsg = error.get_error() assert 'no safe attribute' in error.msg assert etype == 'AttributeError' @pytest.mark.parametrize("nested", [False, True]) def test_naming_exceptions(nested): """ fixing Github issue #137""" interp = make_interpreter(nested_symtable=nested) try_with_named_error = textwrap.dedent(""" try: 2 + '' except Exception as my_error: print(my_error) """) interp(try_with_named_error, raise_errors=True) out = read_stdout(interp) assert 'unsupported operand' in out assert len(interp.error) == 0 if __name__ == '__main__': pytest.main(['-v', '-x', '-s'])