pax_global_header00006660000000000000000000000064144550323740014521gustar00rootroot0000000000000052 comment=ecfcbeb13d95e9cc41ed8b00e69972cec5de76ba asteval-0.9.31/000077500000000000000000000000001445503237400132525ustar00rootroot00000000000000asteval-0.9.31/.codecov.yml000066400000000000000000000004621445503237400154770ustar00rootroot00000000000000codecov: token: 817993c1-edc4-4094-a8ca-09fa767d6336 comment: after_n_builds: 9 coverage: status: project: default: target: auto threshold: 2% informational: true patch: default: target: auto threshold: 10% informational: true asteval-0.9.31/.gitattributes000066400000000000000000000000411445503237400161400ustar00rootroot00000000000000asteval/_version.py export-subst asteval-0.9.31/.github/000077500000000000000000000000001445503237400146125ustar00rootroot00000000000000asteval-0.9.31/.github/dependabot.yml000066400000000000000000000011401445503237400174360ustar00rootroot00000000000000# 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" asteval-0.9.31/.github/workflows/000077500000000000000000000000001445503237400166475ustar00rootroot00000000000000asteval-0.9.31/.github/workflows/macos_numpy.yml000066400000000000000000000012501445503237400217220ustar00rootroot00000000000000name: test on macos, with numpy on: [push] jobs: build: runs-on: macos-latest strategy: fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 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 asteval-0.9.31/.github/workflows/ubuntu_nonumpy.yml000066400000000000000000000013531445503237400225030ustar00rootroot00000000000000name: 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.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 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 asteval-0.9.31/.github/workflows/ubuntu_numpy.yml000066400000000000000000000015671445503237400221550ustar00rootroot00000000000000name: test on ubuntu, with numpy on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 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 python -m pytest --cov=./ --cov-report=xml - name: upload coverage report to codecov uses: codecov/codecov-action@v2 asteval-0.9.31/.github/workflows/windows_numpy.yml000066400000000000000000000012541445503237400223160ustar00rootroot00000000000000name: test on windows, with numpy on: [push] jobs: build: runs-on: windows-latest strategy: fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 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 asteval-0.9.31/.gitignore000066400000000000000000000001461445503237400152430ustar00rootroot00000000000000*.pyc *~ *# .coverage asteval/version.py NonGit/ doc/_build doc/*.pdf build dist *.egg-info MANIFEST asteval-0.9.31/INSTALL000066400000000000000000000005471445503237400143110ustar00rootroot00000000000000Installation instructions for asteval ======================================== To install the asteval module, use:: python setup.py install or pip install asteval Asteval require Python 3.5 or higher. If installed, many functions and constants from numpy will be used by default. Matt Newville Last Update: 14-Nov-2019 asteval-0.9.31/LICENSE000066400000000000000000000021201445503237400142520ustar00rootroot00000000000000The MIT License Copyright (c) 2023 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. asteval-0.9.31/MANIFEST.in000066400000000000000000000004641445503237400150140ustar00rootroot00000000000000include README.txt INSTALL LICENSE MANIFEST.in PKG-INFO include setup.py publish_docs.sh exclude *.pyc core.* *~ *.pdf recursive-include lib *.py recursive-include tests *.py recursive-include doc * recursive-exclude doc/_build * recursive-exclude doc *.pdf include versioneer.py include asteval/_version.py asteval-0.9.31/README.rst000066400000000000000000000062531445503237400147470ustar00rootroot00000000000000ASTEVAL ======= .. image:: https://github.com/newville/asteval/actions/workflows/ubuntu_numpy.yml/badge.svg :target: https://github.com/newville/asteval/actions/workflows/ubuntu_numpy.yml .. image:: https://github.com/newville/asteval/actions/workflows/ubuntu_nonumpy.yml/badge.svg :target: https://github.com/newville/asteval/actions/workflows/ubuntu_nonumpy.yml .. image:: https://github.com/newville/asteval/actions/workflows/macos_numpy.yml/badge.svg :target: https://github.com/newville/asteval/actions/workflows/macos_numpy.yml .. image:: https://github.com/newville/asteval/actions/workflows/windows_numpy.yml/badge.svg :target: https://github.com/newville/asteval/actions/workflows/windows_numpy.yml .. image:: https://codecov.io/gh/newville/asteval/branch/master/graph/badge.svg :target: https://codecov.io/gh/newville/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://newville.github.io/asteval/ .. image:: https://zenodo.org/badge/4185/newville/asteval.svg :target: https://zenodo.org/badge/latestdoi/4185/newville/asteval Links ----- * Documentation: https://newville.github.io/asteval/ * PyPI installation: https://pypi.org/project/asteval/ * Development Code: https://github.com/newville/asteval * Issue Tracker: https://github.com/newville/asteval/issues What is it? ----------- 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, and so many functions from ``numpy`` are imported and used if available. Many Python lanquage 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, tuple, lists, numpy arrays, strings) are fully supported by default. Many of the standard builtin python functions are available, as are all mathemetical 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. 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. asteval-0.9.31/asteval/000077500000000000000000000000001445503237400147115ustar00rootroot00000000000000asteval-0.9.31/asteval/__init__.py000066400000000000000000000016671445503237400170340ustar00rootroot00000000000000""" ASTEVAL provides a numpy-aware, safe(ish) "eval" function Emphasis is on mathematical expressions, and so numpy ufuncs are used if available. Symbols are held in the Interpreter symbol table 'symtable': a simple dictionary supporting a simple, flat namespace. Expressions can be compiled into ast node for later evaluation, using the values in the symbol table current at evaluation time. version: 0.9.31 last update: 2023-July-16 License: MIT Author: Matthew Newville Center for Advanced Radiation Sources, The University of Chicago """ from .asteval import Interpreter from .astutils import (NameFinder, get_ast_names, make_symbol_table, valid_symbol_name) from .version import version as __version__ __all__ = ['Interpreter', 'NameFinder', 'valid_symbol_name', 'make_symbol_table', 'get_ast_names', '__version__'] asteval-0.9.31/asteval/asteval.py000066400000000000000000001116701445503237400167300ustar00rootroot00000000000000#!/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, UNSAFE_ATTRS, ExceptionHolder, ReturnedNone, Empty, make_symbol_table, numpy, op2func, 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.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 self.error is None: self.error = [] if expr is None: expr = self.expr if len(self.error) > 0 and not isinstance(node, ast.Module): msg = f'{msg!s}' err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno) self._interrupt = ast.Raise() self.error.append(err) if self.error_msg is None: self.error_msg = (' '.join([msg, f"at expr='{self.expr}'"])).strip() elif len(msg) > 0: self.error_msg = msg if exc is None: try: exc = self.error[0].exc except: exc = RuntimeError 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) 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. 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 isinstance(node, str): node = self.parse(node) if lineno is not None: self.lineno = lineno if expr is not None: self.expr = 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=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: if len(self.error) == 0: # Unhandled exception that didn't use raise_exception self.raise_exception(node, expr=expr) raise return None 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.start_time = time.time() if isinstance(expr, str): try: node = self.parse(expr) except Exception: errmsg = exc_info()[1] if len(self.error) > 0: errmsg = "\n".join(self.error[0].get_error()) if raise_errors: try: exc = self.error[0].exc except Exception: exc = RuntimeError raise 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) except: errmsg = exc_info()[1] if len(self.error) > 0: errmsg = "\n".join(self.error[0].get_error()) if raise_errors: try: exc = self.error[0].exc except Exception: exc = RuntimeError raise exc(errmsg) if show_errors: print(errmsg, file=self.err_writer) 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 # () def on_ellipsis(self, node): """Ellipses. deprecated in 3.8""" return Ellipsis # 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): #depraction warning: will become: # 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_num(self, node): # ('n',) """Return number. deprecated in 3.8""" return node.n def on_str(self, node): # ('s',) """Return string. deprecated in 3.8""" return node.s def on_bytes(self, node): """return bytes. deprecated in 3.8""" return node.s # ('s',) 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 = '{0}' if node.format_spec is not None: fmt = f'{{0:{self.run(node.format_spec)}}}' return fmt.format(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 on_nameconstant(self, node): """True, False, or None deprecated in 3.8""" return node.value 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) # ctx is ast.Load if not (node.attr in UNSAFE_ATTRS or (node.attr.startswith('__') and node.attr.endswith('__'))): try: return getattr(sym, node.attr) except AttributeError: pass # AttributeError or accessed unsafe attribute msg = f"no attribute '{node.attr}' for {self.run(node.value)}" self.raise_exception(node, exc=AttributeError, msg=msg) return None 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 -- one of the tricky parts.""" val = self.run(node.value) nslice = self.run(node.slice) ctx = node.ctx.__class__ if ctx in (ast.Load, ast.Store): return val[nslice] msg = "subscript with unknown context" self.raise_exception(node, msg=msg) return None 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)) else: msg = "could not delete symbol" self.raise_exception(node, msg=msg) 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 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.node_assign(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] # deprecation warning: will become # if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Constant): if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str): # deprecation warning: will become # doc = nb0.value doc = nb0.value.s 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, args=args, kwargs=kwargs, vararg=vararg, varkws=varkws) if node.name in self.no_deepcopy: self.no_deepcopy.remove(node.name) asteval-0.9.31/asteval/astutils.py000066400000000000000000000633331445503237400171430ustar00rootroot00000000000000""" 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 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 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__') NAME_MATCH = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$").match 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__') # 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 = ('Inf', 'NAN', 'abs', 'add', 'all', 'amax', 'amin', 'angle', 'any', 'append', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'broadcast', 'broadcast_arrays', 'byte', 'c_', 'cdouble', 'ceil', 'cfloat', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conjugate', 'convolve', 'copy', 'copysign', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov', 'cross', 'csingle', 'cumprod', 'cumsum', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'divide', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'empty', 'empty_like', 'equal', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fft', 'fill_diagonal', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'fliplr', 'flipud', 'float32', 'float64', 'float_', 'floating', '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', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int16', 'int32', 'int64', 'int8', 'int_', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'linalg', 'linspace', 'little_endian', 'load', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'mask_indices', 'mat', 'matrix', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum', 'ndarray', 'ndenumerate', 'ndim', 'ndindex', 'negative', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'number', 'obj2sctype', 'ogrid', 'ones', 'ones_like', 'outer', 'packbits', 'percentile', 'pi', 'piecewise', 'place', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 'polyval', 'power', 'prod', 'product', 'ptp', 'put', 'putmask', 'r_', 'rad2deg', 'radians', 'random', 'ravel', 'real', 'real_if_close', 'reciprocal', 'record', 'remainder', 'repeat', 'reshape', 'resize', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'sctype2char', 'searchsorted', 'select', 'setbufsize', 'setdiff1d', 'seterr', 'setxor1d', 'shape', 'short', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'std', 'str_', 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot', 'tile', 'trace', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'ubyte', 'uint', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'union1d', 'unique', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'vsplit', 'vstack', 'where', 'who', '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: numpy_deprecated = [] if int(numpy_version[0]) == 1 and int(numpy_version[1]) >= 20: # aliases deprecated in NumPy v1.20.0 numpy_deprecated = ['str', 'bool', 'int', 'float', 'complex', 'pv', 'rate', 'pmt', 'ppmt', 'npv', 'nper', 'long', 'mirr', 'fv', 'irr', 'ipmt'] if int(numpy_version[0]) == 1 and int(numpy_version[1]) >= 24: # aliases deprecated in NumPy v1.24.0 numpy_deprecated += ['int0', 'uint0', 'bool8'] FROM_NUMPY = tuple(set(FROM_NUMPY) - set(numpy_deprecated)) 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: NUMPY_TABLE[sym] = getattr(numpy, sym) for sname, sym in NUMPY_RENAMES.items(): NUMPY_TABLE[sname] = getattr(numpy, sym) if HAS_NUMPY_FINANCIAL: for sym in FROM_NUMPY_FINANCIAL: NUMPY_TABLE[sym] = getattr(numpy_financial, sym) 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(obj): """type that prevents varargs and varkws""" return type(obj).__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} 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, lineno=None): """TODO: docstring in public method.""" self.node = node self.expr = expr self.msg = msg self.exc = exc self.lineno = lineno 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 = self.exc_info[1] def get_error(self): """Retrieve error data.""" col_offset = -1 if self.node is not None: try: col_offset = self.node.col_offset except AttributeError: pass try: exc_name = self.exc.__name__ except AttributeError: exc_name = str(self.exc) if exc_name in (None, 'None'): exc_name = 'UnknownError' out = [f" {self.expr}"] if col_offset > 0: out.append(f" {col_offset*' '}^^^") out.append(str(self.msg)) return (exc_name, '\n'.join(out)) 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 not valid_varname(name): raise SyntaxError(f"invalid attribute name '{name}'") dict.__setitem__(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: if top: name = '_main' if 'name' in kws: name = kws.pop('name') symtable = Group(name=name) 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._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=0, body=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.__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 ['name'] def __repr__(self): """TODO: docstring in magic method.""" 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}" sig = f"" if self.__doc__ is not None: sig = f"{sig}\n {self.__doc__}" return 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 for node in self.body: self.__asteval__.run(node, expr='<>', lineno=self.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__._calldepth -= 1 symlocals = None return retval asteval-0.9.31/doc/000077500000000000000000000000001445503237400140175ustar00rootroot00000000000000asteval-0.9.31/doc/Makefile000066400000000000000000000063051445503237400154630ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build INSTALLDIR = /home/newville/public_html/asteval/ # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest latexpdf .PHONY: all install html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." asteval.pdf: latex cd $(BUILDDIR)/latex && make all-pdf cp -pr $(BUILDDIR)/latex/asteval.pdf ./asteval.pdf all: html install: all cp -pr $(BUILDDIR)/latex/asteval.pdf $(INSTALLDIR)/asteval.pdf cp -pr $(BUILDDIR)/html/* $(INSTALLDIR)/. help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." 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." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." asteval-0.9.31/doc/_static/000077500000000000000000000000001445503237400154455ustar00rootroot00000000000000asteval-0.9.31/doc/_static/empty000066400000000000000000000000001445503237400165140ustar00rootroot00000000000000asteval-0.9.31/doc/_templates/000077500000000000000000000000001445503237400161545ustar00rootroot00000000000000asteval-0.9.31/doc/_templates/indexsidebar.html000066400000000000000000000004521445503237400215040ustar00rootroot00000000000000

Downloads

Current version: {{ release }}

Downloads: PyPI (Python.org)

try pip install asteval

Development version:
    github.com


asteval-0.9.31/doc/api.rst000066400000000000000000000357301445503237400153320ustar00rootroot00000000000000.. _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 By default, the 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 be low, 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 more that 350 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``. asteval-0.9.31/doc/basics.rst000066400000000000000000000141521445503237400160200ustar00rootroot00000000000000================ 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 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, a very large number (~350) 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 programmming 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 supreess 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) asteval-0.9.31/doc/conf.py000066400000000000000000000151701445503237400153220ustar00rootroot00000000000000# -*- 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 = 'sphinxdoc' # 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 asteval-0.9.31/doc/index.rst000066400000000000000000000073511445503237400156660ustar00rootroot00000000000000.. 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 motivation basics api asteval-0.9.31/doc/installation.rst000066400000000000000000000046451445503237400172630ustar00rootroot00000000000000==================================== Downloading and Installation ==================================== .. _numpy: https://numpy.org/ .. _github: https://github.com/newville/asteval .. _PyPI: https://pypi.org/project/asteval/ Requirements ~~~~~~~~~~~~~~~ Asteval is a pure Python module. For Python 3.8 and higher, there are no required dependencies outside of the standard library. If `numpy`_ and `numpy_financial` are available, Asteval will make use of these libraries. The test suite requires the `pytest` and `coverage` modules, and building the documentation requires `sphinx`. The latest stable version of asteval is |release|. Versions 0.9.30 and later support Python 3.8 through 3.11 and are and are automatically tested with these on Windows, MacOS, and Linux, with and without `numpy`_ installed. Python versions have generally been supported by `asteval` until they are well past the end of security fixes - there are no immediate plans to drop support for Python 3.7, though we are no longer test with it. 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. At this writing (Asteval 0.9.31, July, 2023), minimal testing has been done with Python 3.12-beta4, without numpy installed. All tests pass, which suggests that there no changes needed to the way `asteval` works with the AST generated by Python. Download and Installation ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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/newville/asteval.git Installation ~~~~~~~~~~~~~~~~~ Installation from source on any platform is:: pip install . License ~~~~~~~~~~~~~ The ASTEVAL code is distribution under the following license: .. literalinclude:: ../LICENSE asteval-0.9.31/doc/motivation.rst000066400000000000000000000225671445503237400167560ustar00rootroot00000000000000.. _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. 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. * 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`` 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. An important caveat is that asteval will typically expose numpy ``ufuncs`` from the numpy module. Several of these can seg-fault Python without too much trouble. If you are paranoid about safe user input that can never cause a segmentation fault, you may want to consider disabling the use of numpy, or take extra care to specify what can be used. There are important categories of safety that asteval does not even attempt to address. 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)) """ aeval.eval(txt) can take a noticeable amount of CPU time - if it does not, changing ``1e8`` to ``9e13`` almost certainly will. As another example, consider the expression ``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``, will cause the statement to take several seconds. 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 anyones threshold for an acceptable run-time. 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 this exponentiation example, asteval will raise a runtime error, telling you that an exponent > 10,000 is not allowed. But that happens at runtime, after the value of the exponent has been evaluated, it does not happen by looking at the text of the code. And, there is no limit on the size of arrays that can be created because a check would have to done at runtime. There are countless other "clever ways" to have very long run times that cannot be readily predicted from the text. The exponential example also demonstrates 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 would not be 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 li`mit 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(...) A secondary security concern is that the default list of supported functions does include Python's ``open()`` which will allow disk access to the untrusted user. If ``numpy`` is supported, its ``load()`` and ``loadtxt()`` functions will also normally be supported. Including these functions does not elevate permissions, but it does allow the user of the asteval interpreter 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. 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. asteval-0.9.31/pyproject.toml000066400000000000000000000003031445503237400161620ustar00rootroot00000000000000[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" asteval-0.9.31/requirements.txt000066400000000000000000000002161445503237400165350ustar00rootroot00000000000000## ## pip requirements file. To install dependencies, use ## ## pip install -r requirements.txt importlib_metadata ; python_version < '3.8' asteval-0.9.31/setup.cfg000066400000000000000000000034351445503237400151000ustar00rootroot00000000000000[metadata] name = asteval description = Safe, minimalistic evaluator of python expression using ast module long_description = ASTEVAL provides a numpy-aware, safe(ish) 'eval' function Emphasis is on mathematical expressions, and so numpy ufuncs are used if available. Symbols are held in the Interpreter symbol table 'symtable': a simple dictionary supporting a simple, flat namespace. Expressions can be compiled into ast node for later evaluation, using the values in the symbol table current at evaluation time. author = Matthew Newville author_email = matt.newville@gmail.com url = https://github.com/newville/asteval license = MIT License platforms = any classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: Implementation :: PyPy project_urls = Source = https://github.com/newville/asteval Documentation = https://newville.github.io/asteval/ Tracker = https://github.com/newville/asteval/issues [options] packages = find: include_package_data = True python_requires = >=3.7 setup_requires = setuptools_scm test_requires = pytest install_requires = importlib_metadata ; python_version < "3.8" [options.packages.find] include = asteval [options.extras_require] dev = build twine doc = Sphinx test = coverage pytest pytest-cov all = %(dev)s %(test)s %(doc)s [coverage:run] omit = tests/* [tool:pytest] addopts = --cov=asteval --cov-report xml asteval-0.9.31/setup.py000066400000000000000000000001321445503237400147600ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup if __name__ == "__main__": setup() asteval-0.9.31/tests/000077500000000000000000000000001445503237400144145ustar00rootroot00000000000000asteval-0.9.31/tests/test_asteval.py000066400000000000000000001330721445503237400174720ustar00rootroot00000000000000#!/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_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_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.Num) assert astnode.body[0].targets[0].id == 'x' assert astnode.body[0].value.n == 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' if __name__ == '__main__': pytest.main(['-v', '-x', '-s']) asteval-0.9.31/tests/test_asteval_orig.py000066400000000000000000001224701445503237400205120ustar00rootroot00000000000000#!/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 HAS_NUMPY = False try: import numpy as np from numpy.testing import assert_allclose HAS_NUMPY = True except ImportError: HAS_NUMPY = False nested = False class TestCase(unittest.TestCase): """testing of asteval""" def setUp(self): "setup" self.interp = Interpreter(nested_symtable=nested) self.symtable = self.interp.symtable self.set_stdout() self.set_stderr() def set_stdout(self): "stdout" self.stdout = NamedTemporaryFile('w', delete=False, prefix='astevaltest') self.interp.writer = self.stdout def read_stdout(self): "read stdout" self.stdout.close() time.sleep(0.1) fname = self.stdout.name with open(self.stdout.name) as inp: out = inp.read() self.set_stdout() os.unlink(fname) return out def set_stderr(self): "sterr" self.stderr = NamedTemporaryFile('w', delete=False, prefix='astevaltest_stderr') self.interp.err_writer = self.stderr def read_stderro(self): self.stderr.close() time.sleep(0.1) fname = self.stderr.name with open(self.stderr.name) as inp: out = inp.read() self.set_stderr() os.unlink(fname) return out def tearDown(self): if not self.stdout.closed: self.stdout.close() if not self.stderr.closed: self.stderr.close() # noinspection PyBroadException try: os.unlink(self.stdout.name) except: pass try: os.unlink(self.stderr.name) except: pass # noinspection PyUnresolvedReferences def isvalue(self, sym, val): """assert that a symboltable symbol has a particular value""" tval = self.interp.symtable[sym] if HAS_NUMPY and isinstance(val, np.ndarray): assert_allclose(tval, val, rtol=0.01) else: assert tval == val def isnear(self, expr, val): tval = self.interp(expr) if HAS_NUMPY: assert_allclose(tval, val, rtol=1.e-4, atol=1.e-4) # noinspection PyUnresolvedReferences def istrue(self, expr): """assert that an expression evaluates to True""" val = self.interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return self.assertTrue(val) # noinspection PyUnresolvedReferences def isfalse(self, expr): """assert that an expression evaluates to False""" val = self.interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return self.assertFalse(val) def check_output(self, chk_str, exact=False): self.interp.writer.flush() out = self.read_stdout().split('\n') if out: if exact: return chk_str == out[0] return chk_str in out[0] return False def check_error(self, chk_type='', chk_msg=''): try: errtype, errmsg = self.interp.error[0].get_error() self.assertEqual(errtype, chk_type) if chk_msg: self.assertTrue(chk_msg in errmsg) except IndexError: if chk_type: self.assertTrue(False) class TestEval(TestCase): """testing of asteval""" def test_py3(self): assert version_info.major > 2 def test_dict_index(self): """dictionary indexing""" self.interp("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") self.istrue("a_dict['a'] == 1") self.istrue("a_dict['d'] == 4") def test_dict_set_index(self): """dictionary indexing""" self.interp("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") self.interp("a_dict['a'] = -4") self.interp("a_dict['e'] = 73") self.istrue("a_dict['a'] == -4") self.istrue("a_dict['e'] == 73") self.interp("b_dict = {}") self.interp("keyname = 'a'") self.interp("b_dict[keyname] = (1, -1, 'x')") self.istrue("b_dict[keyname] == (1, -1, 'x')") def test_list_index(self): """list indexing""" self.interp("a_list = ['a', 'b', 'c', 'd', 'o']") self.istrue("a_list[0] == 'a'") self.istrue("a_list[1] == 'b'") self.istrue("a_list[2] == 'c'") def test_tuple_index(self): """tuple indexing""" self.interp("a_tuple = (5, 'a', 'x')") self.istrue("a_tuple[0] == 5") self.istrue("a_tuple[2] == 'x'") def test_string_index(self): """string indexing""" self.interp("a_string = 'hello world'") self.istrue("a_string[0] == 'h'") self.istrue("a_string[6] == 'w'") self.istrue("a_string[-1] == 'd'") self.istrue("a_string[-2] == 'l'") def test_sets(self): """build, use set""" self.interp("a_set = {'a', 'b', 'c', 'd', 'c'}") self.istrue("len(a_set) == 4") self.istrue("'b' in a_set") self.interp("c_major7 = {'c', 'e', 'g', 'b'}") self.interp("d_minor7 = {'d', 'f', 'a', 'c'}") self.interp("e_minor7 = {'e', 'g', 'b', 'd'}") self.interp("f_major7 = {'f', 'a', 'c', 'e'}") self.interp("g_dom7 = {'g', 'b', 'd', 'f'}") self.interp("a_minor7 = {'a', 'c', 'e', 'g'}") self.interp("b_halfdim = {'b', 'd', 'f', 'a'}") self.interp("c_diatonic = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}") self.interp("phrase = d_minor7 + g_dom7 + c_major7") self.check_error('TypeError') self.istrue("c_major7 & d_minor7 == {'c'}") self.istrue("c_major7 & e_minor7 == {'b', 'g', 'e'}") self.istrue("c_major7 | d_minor7 == c_diatonic") def test_basic(self): """build, use set""" v = self.interp("4") assert v == 4 v = self.interp("'x'") assert v == 'x' v = self.interp("b'x'") assert v == b'x' v = self.interp("str(4)") assert v == '4' v = self.interp("repr(4)") assert v == '4' v = self.interp("...") assert v == ... v = self.interp("False") assert v == False self.interp("x = 8") self.interp("x.foo = 3") self.check_error('AttributeError') self.interp("del x") def test_fstring(self): "fstrings" self.interp("x = 2523.33/723") self.interp("s = f'{x:+.3f}'") self.istrue("s == '+3.490'") self.interp("chie = '\u03c7(E)'") self.interp("v_s = f'{chie!s}'") self.interp("v_r = f'{chie!r}'") self.interp("v_a = f'{chie!a}'") self.istrue("v_s == '\u03c7(E)'") self.istrue('''v_r == "'\u03c7(E)'"''') self.istrue('''v_a == "'\\\\u03c7(E)'"''') def test_verylong_strings(self): "test that long string raises an error" longstr = "statement_of_somesize" * 5000 self.interp(longstr) self.check_error('RuntimeError') def test_ndarray_index(self): """nd array indexing""" if HAS_NUMPY: self.interp("a_ndarray = 5*arange(20)") assert self.interp("a_ndarray[2]") == 10 assert self.interp("a_ndarray[4]") == 20 def test_ndarrayslice(self): """array slicing""" if HAS_NUMPY: self.interp("a_ndarray = arange(200).reshape(10, 20)") self.istrue("a_ndarray[1:3,5:7] == array([[25,26], [45,46]])") self.interp("y = arange(20).reshape(4, 5)") self.istrue("y[:,3] == array([3, 8, 13, 18])") self.istrue("y[...,1] == array([1, 6, 11, 16])") self.istrue("y[1,:] == array([5, 6, 7, 8, 9])") self.interp("y[...,1] = array([2, 2, 2, 2])") self.istrue("y[1,:] == array([5, 2, 7, 8, 9])") def test_while(self): """while loops""" self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 """)) self.isvalue('n', 8) self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 if n > 3: break else: n = -1 """)) self.isvalue('n', 4) self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 else: n = -1 """)) self.isvalue('n', -1) self.interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) self.isvalue('n', 10) self.isvalue('i', 5) self.interp(textwrap.dedent(""" n=0 while n < 10: n += 1 print( ' n = ', n) if n > 5: break print( 'finish: n = ', n) """)) self.isvalue('n', 6) def test_while_continue(self): self.interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) self.isvalue('n', 10) self.isvalue('i', 5) def test_while_break(self): self.interp(textwrap.dedent(""" n = 0 while n < 10: n += 1 if n > 6: break print( 'finish: n = ', n) """)) self.isvalue('n', 7) def test_with(self): "test with" 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('\\', '/') self.interp(textwrap.dedent(""" with open('{0}', 'r') as fh: lines = fh.readlines() """.format(fname))) lines = self.interp.symtable['lines'] fh1 = self.interp.symtable['fh'] assert fh1.closed assert len(lines) > 2 assert lines[1].startswith('line') # noinspection PyTypeChecker def test_assert(self): """test assert statements""" self.interp.error = [] self.interp('n=6') self.interp('assert n==6') self.check_error(None) self.interp('assert n==7') self.check_error('AssertionError') self.interp('assert n==7, "no match"') self.check_error('AssertionError', 'no match') def test_for(self): """for loops""" self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i """)) self.isvalue('n', 45) self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i else: n = -1 """)) self.isvalue('n', -1) if HAS_NUMPY: self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i """)) self.isvalue('n', 45) self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i else: n = -1 """)) self.isvalue('n', -1) def test_for_break(self): self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i if n > 2: break else: n = -1 """)) self.isvalue('n', 3) if HAS_NUMPY: self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i if n > 2: break else: n = -1 """)) self.isvalue('n', 3) def test_if(self): """runtime errors test""" self.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 """)) self.isvalue('x', 2) self.isvalue('y', 33) def test_print(self): """print (ints, str, ....)""" self.interp("print(31)") self.check_output('31\n', True) self.interp("print('%s = %.3f' % ('a', 1.2012345))") self.check_output('a = 1.201\n', True) self.interp("print('{0:s} = {1:.2f}'.format('a', 1.2012345))") self.check_output('a = 1.20\n', True) def test_repr(self): """repr of dict, list""" self.interp("x = {'a': 1, 'b': 2, 'c': 3}") self.interp("y = ['a', 'b', 'c']") self.interp("rep_x = repr(x['a'])") self.interp("rep_y = repr(y)") self.interp("rep_y , rep_x") self.interp("repr(None)") self.isvalue("rep_x", "1") self.isvalue("rep_y", "['a', 'b', 'c']") def test_cmp(self): """numeric comparisons""" self.istrue("3 == 3") self.istrue("3.0 == 3") self.istrue("3.0 == 3.0") self.istrue("3 != 4") self.istrue("3.0 != 4") self.istrue("3 >= 1") self.istrue("3 >= 3") self.istrue("3 <= 3") self.istrue("3 <= 5") self.istrue("3 < 5") self.istrue("5 > 3") self.isfalse("3 == 4") self.isfalse("3 > 5") self.isfalse("5 < 3") def test_bool(self): """boolean logic""" self.interp(textwrap.dedent(""" yes = True no = False nottrue = False a = range(7)""")) self.istrue("yes") self.isfalse("no") self.isfalse("nottrue") self.isfalse("yes and no or nottrue") self.isfalse("yes and (no or nottrue)") self.isfalse("(yes and no) or nottrue") self.istrue("yes or no and nottrue") self.istrue("yes or (no and nottrue)") self.isfalse("(yes or no) and nottrue") self.istrue("yes or not no") self.istrue("(yes or no)") self.isfalse("not (yes or yes)") self.isfalse("not (yes or no)") self.isfalse("not (no or yes)") self.istrue("not no or yes") self.isfalse("not yes") self.istrue("not no") def test_bool_coerce(self): """coercion to boolean""" self.istrue("1") self.isfalse("0") self.istrue("'1'") self.isfalse("''") self.istrue("[1]") self.isfalse("[]") self.istrue("(1)") self.istrue("(0,)") self.isfalse("()") self.istrue("dict(y=1)") self.isfalse("{}") # noinspection PyUnresolvedReferences def test_assignment(self): """variables assignment""" self.interp('n = 5') self.isvalue("n", 5) self.interp('s1 = "a string"') self.isvalue("s1", "a string") self.interp('b = (1,2,3)') self.isvalue("b", (1, 2, 3)) if HAS_NUMPY: self.interp('a = 1.*arange(10)') self.isvalue("a", np.arange(10)) self.interp('a[1:5] = 1 + 0.5 * arange(4)') self.isnear("a", np.array([0., 1., 1.5, 2., 2.5, 5., 6., 7., 8., 9.])) def test_names(self): """names test""" self.interp('nx = 1') self.interp('nx1 = 1') # use \u escape b/c python 2 complains about file encoding self.interp('\u03bb = 1') self.interp('\u03bb1 = 1') def test_syntaxerrors_1(self): """assignment syntax errors test""" 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: self.interp(expr, show_errors=False, raise_errors=True) except: failed = True self.assertTrue(failed) self.check_error('SyntaxError') def test_unsupportednodes(self): """unsupported nodes""" for expr in ('f = lambda x: x*x', 'yield 10'): failed = False # noinspection PyBroadException try: self.interp(expr, show_errors=False, raise_errors=True) except: failed = True self.assertTrue(failed) self.check_error('NotImplementedError') def test_syntaxerrors_2(self): """syntax errors test""" for expr in ('x = (1/*)', 'x = 1.A', 'x = A.2'): failed = False # noinspection PyBroadException try: self.interp(expr, show_errors=False, raise_errors=True) except: # RuntimeError: failed = True self.assertTrue(failed) self.check_error('SyntaxError') def test_runtimeerrors_1(self): """runtime errors test""" self.interp("zero = 0") self.interp("astr ='a string'") self.interp("atup = ('a', 'b', 11021)") self.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: self.interp(expr, show_errors=False, raise_errors=True) except: failed = True self.assertTrue(failed) self.check_error(errname) # noinspection PyUnresolvedReferences def test_ndarrays(self): """simple ndarrays""" if HAS_NUMPY: self.interp('n = array([11, 10, 9])') self.istrue("isinstance(n, ndarray)") self.istrue("len(n) == 3") self.isvalue("n", np.array([11, 10, 9])) self.interp('n = arange(20).reshape(5, 4)') self.istrue("isinstance(n, ndarray)") self.istrue("n.shape == (5, 4)") self.interp("myx = n.shape") self.interp("n.shape = (4, 5)") self.istrue("n.shape == (4, 5)") self.interp("a = arange(20)") self.interp("gg = a[1:13:3]") self.isvalue('gg', np.array([1, 4, 7, 10])) self.interp("gg[:2] = array([0,2])") self.isvalue('gg', np.array([0, 2, 7, 10])) self.interp('a, b, c, d = gg') self.isvalue('c', 7) self.istrue('(a, b, d) == (0, 2, 10)') def test_binop(self): """test binary ops""" self.interp('a = 10.0') self.interp('b = 6.0') self.istrue("a+b == 16.0") self.isnear("a-b", 4.0) self.istrue("a/(b-1) == 2.0") self.istrue("a*b == 60.0") def test_unaryop(self): """test binary ops""" self.interp('a = -10.0') self.interp('b = -6.0') self.isnear("a", -10.0) self.isnear("b", -6.0) def test_del(self): """test del function""" self.interp('a = -10.0') self.interp('b = -6.0') self.assertTrue('a' in self.symtable) self.assertTrue('b' in self.symtable) self.interp("del a") self.interp("del b") self.assertFalse('a' in self.symtable) self.assertFalse('b' in self.symtable) # noinspection PyUnresolvedReferences def test_math1(self): """builtin math functions""" self.interp('n = sqrt(4)') self.istrue('n == 2') self.isnear('sin(pi/2)', 1) self.isnear('cos(pi/2)', 0) self.istrue('exp(0) == 1') if HAS_NUMPY: self.isnear('exp(1)', np.e) def test_namefinder(self): """test namefinder""" p = self.interp.parse('x+y+cos(z)') nf = NameFinder() nf.generic_visit(p) self.assertTrue('x' in nf.names) self.assertTrue('y' in nf.names) self.assertTrue('z' in nf.names) self.assertTrue('cos' in nf.names) def test_list_comprehension(self): """test list comprehension""" self.interp('x = [i*i for i in range(4)]') self.isvalue('x', [0, 1, 4, 9]) self.interp('x = [i*i for i in range(6) if i > 1]') self.isvalue('x', [4, 9, 16, 25]) self.interp('x = [(i, j*2) for i in range(6) for j in range(2)]') self.isvalue('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)]) self.interp.readonly_symbols = set('a') list_in = "x = [a*2 for a in range(5)]" self.interp(list_in) self.check_error('NameError') self.interp.readonly_symbols = set() def test_set_comprehension(self): """test set comprehension""" 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)} self.interp(set_in) self.isvalue("x", set_out) def test_dict_comprehension(self): """test set comprehension""" 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} self.interp(dict_in) self.isvalue('x', dict_out) dict_in = "x = {a:yield for a in range(5) for yield in range(4)}" self.interp(dict_in) self.check_error('SyntaxError') def test_ifexp(self): """test if expressions""" self.interp('x = 2') self.interp('y = 4 if x > 0 else -1') self.interp('z = 4 if x > 3 else -1') self.isvalue('y', 4) self.isvalue('z', -1) # noinspection PyUnresolvedReferences def test_index_assignment(self): """test indexing / subscripting on assignment""" if HAS_NUMPY: self.interp('x = arange(10)') self.interp('l = [1,2,3,4,5]') self.interp('l[0] = 0') self.interp('l[3] = -1') self.isvalue('l', [0, 2, 3, -1, 5]) self.interp('l[0:2] = [-1, -2]') self.isvalue('l', [-1, -2, 3, -1, 5]) self.interp('x[1] = 99') self.isvalue('x', np.array([0, 99, 2, 3, 4, 5, 6, 7, 8, 9])) self.interp('x[0:2] = [9,-9]') self.isvalue('x', np.array([9, -9, 2, 3, 4, 5, 6, 7, 8, 9])) def test_reservedwords(self): """test reserved words""" for w in ('and', 'as', 'while', 'raise', 'else', 'class', 'del', 'def', 'import', 'None'): self.interp.error = [] # noinspection PyBroadException try: self.interp("%s= 2" % w, show_errors=False, raise_errors=True) except: pass self.check_error('SyntaxError') for w in ('True', 'False'): self.interp.error = [] self.interp("%s= 2" % w) self.check_error('SyntaxError') for w in ('eval', '__import__'): self.interp.error = [] self.interp("%s= 2" % w) self.check_error('NameError') def test_raise(self): """test raise""" self.interp("raise NameError('bob')") self.check_error('NameError', 'bob') def test_tryexcept(self): """test try/except""" self.interp(textwrap.dedent(""" x = 5 try: x = x/0 except ZeroDivisionError: print( 'Error Seen!') x = -999 """)) self.isvalue('x', -999) self.interp(textwrap.dedent(""" x = -1 try: x = x/0 except ZeroDivisionError: pass """)) self.isvalue('x', -1) self.interp(textwrap.dedent(""" x = 15 try: raise Exception() x = 20 except: pass """)) self.isvalue('x', 15) def test_tryelsefinally(self): self.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 """)) self.interp("val, ok, clean = dotry(1, 2.0)") self.interp("print(ok, clean)") self.isnear("val", 0.5) self.isvalue("ok", True) self.isvalue("clean", True) self.interp("val, ok, clean = dotry(1, 0.0)") self.isvalue("val", -1) self.isvalue("ok", False) self.isvalue("clean", True) def test_function1(self): """test function definition and running""" self.interp(textwrap.dedent(""" def fcn(x, scale=2): 'test function' out = sqrt(x) if scale > 1: out = out * scale return out """)) self.interp("a = fcn(4, scale=9)") self.isvalue("a", 18) self.interp("a = fcn(9, scale=0)") self.isvalue("a", 3) self.interp("print(fcn)") self.check_output(' 5: return 1 return -1 def b(): return 2.5 def c(x=10): x = a(x=x) y = b() return x + y """ self.interp(textwrap.dedent(setup)) self.interp("o1 = c()") self.interp("o2 = c(x=0)") self.isvalue('o1', 3.5) self.isvalue('o2', 1.5) def test_astdump(self): """test ast parsing and dumping""" astnode = self.interp.parse('x = 1') self.assertTrue(isinstance(astnode, ast.Module)) self.assertTrue(isinstance(astnode.body[0], ast.Assign)) self.assertTrue(isinstance(astnode.body[0].targets[0], ast.Name)) self.assertTrue(isinstance(astnode.body[0].value, ast.Num)) self.assertTrue(astnode.body[0].targets[0].id == 'x') self.assertTrue(astnode.body[0].value.n == 1) dumped = self.interp.dump(astnode.body[0]) self.assertTrue(dumped.startswith('Assign')) # noinspection PyTypeChecker def test_safe_funcs(self): self.interp("'*'*(2<<17)") self.check_error(None) self.interp("'*'*(1+2<<17)") self.check_error('RuntimeError') self.interp("'*'*(2<<17) + '*'") self.check_error('RuntimeError') self.interp("1.01**10000") self.check_error(None) self.interp("1.01**10001") self.check_error('RuntimeError') self.interp("1.5**10000") self.check_error('OverflowError') self.interp("1<<1000") self.check_error(None) self.interp("1<<1001") self.check_error('RuntimeError') def test_safe_open(self): self.interp('open("foo1", "wb")') self.check_error('RuntimeError') self.interp('open("foo2", "rb")') self.check_error('FileNotFoundError') self.interp('open("foo3", "rb", 2<<18)') self.check_error('RuntimeError') def test_recursionlimit(self): self.interp("""def foo(): return foo()\nfoo()""") self.check_error('RecursionError') def test_kaboom(self): """ test Ned Batchelder's 'Eval really is dangerous' - Kaboom test (and related tests)""" self.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,""),{})() )()""") self.check_error('NotImplementedError') # Safe, lambda is not supported self.interp( """[print(c) for c in ().__class__.__bases__[0].__subclasses__()]""") # Try a portion of the kaboom... self.check_error('AttributeError', '__class__') # Safe, unsafe dunders are not supported self.interp("9**9**9**9**9**9**9**9") self.check_error('RuntimeError') # Safe, safe_pow() catches this s = 'x = ' + '('*100 + '1' + ')'*100 self.interp(s) if version_info.minor > 8: self.isvalue('x', 1) self.check_error(None) else: self.check_error('RuntimeError') # Hmmm, this is caught, but its still concerning... self.interp("compile('xxx')") self.check_error('NameError') # Safe, compile() is not supported def test_exit_value(self): """test expression eval - last exp. is returned by interpreter""" z = self.interp("True") self.assertTrue(z) z = self.interp("x = 1\ny = 2\ny == x + x\n") self.assertTrue(z) z = self.interp("x = 42\nx") self.assertEqual(z, 42) self.isvalue('x', 42) z = self.interp("""def foo(): return 42\nfoo()""") self.assertEqual(z, 42) def test_removenodehandler(self): handler = self.interp.remove_nodehandler('ifexp') self.interp('testval = 300') self.interp('bogus = 3 if testval > 100 else 1') self.check_error('NotImplementedError') self.interp.set_nodehandler('ifexp', handler) self.interp('bogus = 3 if testval > 100 else 1') self.isvalue('bogus', 3) def test_set_default_nodehandler(self): handler_import = self.interp.set_nodehandler('import') handler_importfrom = self.interp.set_nodehandler('importfrom') self.interp('import ast') self.check_error(None) self.interp('import notavailable') self.check_error('ImportError') self.interp('from time import ctime, strftime') self.check_error(None) self.interp('from time import ctime as tclock, strftime as s') self.check_error(None) self.interp('import ast as pyast') self.check_error(None) self.interp.remove_nodehandler('import') self.interp.remove_nodehandler('importfrom') self.interp('from time import ctime') self.check_error('NotImplementedError') def test_interpreter_opts(self): i1 = Interpreter(no_ifexp=True) assert i1.node_handlers['ifexp'] == i1.unimplemented i1('y = 4 if x > 0 else -1') errtype, errmsg = i1.error[0].get_error() self.assertEqual(errtype, 'NotImplementedError') conf = {k: v for k, v in i1.config.items()} conf['ifexp'] = True imin = Interpreter(minimal=True) 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) 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) assert i2.node_handlers['ifexp'] != i2.unimplemented assert i2.node_handlers['import'] == i2.unimplemented def test_get_user_symbols(self): self.interp("x = 1.1\ny = 2.5\nz = 788\n") usersyms = self.interp.user_defined_symbols() assert 'x' in usersyms assert 'y' in usersyms assert 'z' in usersyms assert 'foo' not in usersyms def test_custom_symtable(self): "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) 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) def test_numpy_renames_in_custom_symtable(self): """test that numpy renamed functions are in symtable""" if HAS_NUMPY: sym_table = make_symbol_table(nested=False) assert "ln" in sym_table sym_table = make_symbol_table(nested=True) lnfunc = sym_table.get('ln', None) assert lnfunc is not None def test_readonly_symbols(self): 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 def test_chained_compparisons(self): self.interp('a = 7') self.interp('b = 12') self.interp('c = 19') self.interp('d = 30') self.assertTrue(self.interp('a < b < c < d')) self.assertFalse(self.interp('a < b < c/88 < d')) self.assertFalse(self.interp('a < b < c < d/2')) def test_array_compparisons(self): if HAS_NUMPY: self.interp("sarr = arange(8)") sarr = np.arange(8) ox1 = self.interp("sarr < 4.3") assert np.all(ox1 == (sarr < 4.3)) ox1 = self.interp("sarr == 4") assert np.all(ox1 == (sarr == 4)) def test_minimal(self): aeval = Interpreter(builtins_readonly=True, minimal=True) aeval("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") self.assertTrue(aeval("a_dict['a'] == 1")) self.assertTrue(aeval("a_dict['c'] == 3")) def test_partial_exception(self): sym_table = make_symbol_table(sqrt=partial(math.sqrt)) 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 def test_inner_return(self): self.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 = self.interp("func()") assert out == (0, 4, 5) def test_nested_break(self): self.interp(textwrap.dedent(""" def func_w(): for k in range(5): if k == 4: break k = 100 return k """)) assert 4 == self.interp("func_w()") def test_pow(self): assert 2**-2 == self.interp("2**-2") def test_stringio(): """ test using stringio for output/errors """ out = StringIO() err = StringIO() intrep = Interpreter(writer=out, err_writer=err) intrep("print('out')") assert out.getvalue() == 'out\n' if __name__ == '__main__': pytest.main(['-v', '-x', '-s'])