pax_global_header00006660000000000000000000000064140643474210014517gustar00rootroot0000000000000052 comment=b50f7d3f7a283bd9b9951cd47a27a9d613331b87 asteval-0.9.25/000077500000000000000000000000001406434742100132535ustar00rootroot00000000000000asteval-0.9.25/.gitattributes000066400000000000000000000000411406434742100161410ustar00rootroot00000000000000asteval/_version.py export-subst asteval-0.9.25/.github/000077500000000000000000000000001406434742100146135ustar00rootroot00000000000000asteval-0.9.25/.github/workflows/000077500000000000000000000000001406434742100166505ustar00rootroot00000000000000asteval-0.9.25/.github/workflows/test-python.yml000066400000000000000000000021571406434742100216760ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: [3.6, 3.7, 3.8, 3.9] 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 numpy pip setuptools codecov pytest pytest-cov coverage if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Test with pytest run: | python setup.py install cd tests coverage run --source=asteval -m pytest coverage report -m bash <(curl -s https://codecov.io/bash) asteval-0.9.25/.github/workflows/test-python_pydevel.yml000066400000000000000000000022041406434742100234170ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python Development version on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: [3.9, '3.10.0-beta.1'] 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 numpy==1.18 pip setuptools codecov pytest pytest-cov coverage if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Test with pytest run: | python setup.py install cd tests coverage run --source=asteval -m pytest coverage report -m bash <(curl -s https://codecov.io/bash) asteval-0.9.25/.gitignore000066400000000000000000000001231406434742100152370ustar00rootroot00000000000000*.pyc *~ *# .coverage NonGit/ doc/_build doc/*.pdf build dist *.egg-info MANIFEST asteval-0.9.25/INSTALL000066400000000000000000000005471406434742100143120ustar00rootroot00000000000000Installation 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.25/LICENSE000066400000000000000000000021201406434742100142530ustar00rootroot00000000000000The MIT License Copyright (c) 2021 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.25/MANIFEST.in000066400000000000000000000004641406434742100150150ustar00rootroot00000000000000include 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.25/README.rst000066400000000000000000000052251406434742100147460ustar00rootroot00000000000000ASTEVAL ======= .. image:: https://github.com/newville/asteval/actions/workflows/test-python.yml/badge.svg :target: https://github.com/newville/asteval/actions/workflows/test-python.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.25/asteval/000077500000000000000000000000001406434742100147125ustar00rootroot00000000000000asteval-0.9.25/asteval/__init__.py000066400000000000000000000016361406434742100170310ustar00rootroot00000000000000""" 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.13 last update: 2018-Sept-29 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) __all__ = ['Interpreter', 'NameFinder', 'valid_symbol_name', 'make_symbol_table', 'get_ast_names'] from ._version import __version__ asteval-0.9.25/asteval/_version.py000066400000000000000000000006731406434742100171160ustar00rootroot00000000000000__date__ = '2021-Jun-21' __authors__ = "M. Newville" __release_version__ = '0.9.24' try: # python >=3.8 from importlib.metadata import version, PackageNotFoundError except ImportError: # python <3.8 # importlib.metadata not available for python 3.7 from importlib_metadata import version, PackageNotFoundError try: __version__ = version("asteval") except PackageNotFoundError: __version__ = __release_version__ asteval-0.9.25/asteval/asteval.py000066400000000000000000001032771406434742100167350ustar00rootroot00000000000000#!/usr/bin/env python """Safe(ish) evaluation of mathematical expression 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 simple, 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 'import' and 'eval') are simply not allowed. Many parts of Python syntax are supported, including: for loops, while loops, if-then-elif-else conditionals try-except (including 'finally') function definitions with def advanced slicing: a[::-1], array[-3:, :, ::2] if-expressions: out = one_thing if TEST else other list comprehension out = [sqrt(i) for i in values] 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) """ import ast import inspect import time from sys import exc_info, stderr, stdout from .astutils import (HAS_NUMPY, UNSAFE_ATTRS, ExceptionHolder, ReturnedNone, make_symbol_table, numpy, op2func, valid_symbol_name) ALL_NODES = ['arg', 'assert', 'assign', 'attribute', 'augassign', 'binop', 'boolop', 'break', 'call', 'compare', 'continue', 'delete', 'dict', 'ellipsis', 'excepthandler', 'expr', 'extslice', 'for', 'functiondef', 'if', 'ifexp', 'index', 'interrupt', 'list', 'listcomp', 'module', 'name', 'nameconstant', 'num', 'pass', 'raise', 'repr', 'return', 'slice', 'str', 'subscript', 'try', 'tuple', 'unaryop', 'while', 'constant'] class Interpreter: """create an asteval Interpreter: a restricted, simplified interpreter of mathematical expressions using Python syntax. Parameters ---------- symtable : dict or `None` dictionary to use as symbol table (if `None`, one will be created). usersyms : 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. minimal : bool create a minimal interpreter: disable all options (see Note 1). no_if : bool whether to support `if` blocks no_for : bool whether to support `for` blocks. no_while : bool whether to support `while` blocks. no_try : bool whether to support `try` blocks. no_functiondef : bool whether to support user-defined functions. no_ifexp : bool whether to support if expressions. no_listcomp : bool whether to support list comprehension. no_augassign : bool whether to support augemented assignments (`a += 1`, etc). no_assert : bool whether to support `assert`. no_delete : bool whether to support `del`. no_raise : bool whether to support `raise`. no_print : bool whether to support `print`. 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 Notes ----- 1. setting `minimal=True` is equivalent to setting all `no_***` options to `True`. """ def __init__(self, symtable=None, usersyms=None, writer=None, err_writer=None, use_numpy=True, minimal=False, no_if=False, no_for=False, no_while=False, no_try=False, no_functiondef=False, no_ifexp=False, no_listcomp=False, no_augassign=False, no_assert=False, no_delete=False, no_raise=False, no_print=False, max_time=None, readonly_symbols=None, builtins_readonly=False): self.writer = writer or stdout self.err_writer = err_writer or stderr if symtable is None: if usersyms is None: usersyms = {} symtable = make_symbol_table(use_numpy=use_numpy, **usersyms) self.symtable = symtable self._interrupt = None self.error = [] self.error_msg = None self.expr = None self.retval = None self.lineno = 0 self.start_time = time.time() self.use_numpy = HAS_NUMPY and use_numpy symtable['print'] = self._printer self.no_print = no_print or minimal nodes = ALL_NODES[:] if minimal or no_if: nodes.remove('if') if minimal or no_for: nodes.remove('for') if minimal or no_while: nodes.remove('while') if minimal or no_try: nodes.remove('try') if minimal or no_functiondef: nodes.remove('functiondef') if minimal or no_ifexp: nodes.remove('ifexp') if minimal or no_assert: nodes.remove('assert') if minimal or no_delete: nodes.remove('delete') if minimal or no_raise: nodes.remove('raise') if minimal or no_listcomp: nodes.remove('listcomp') if minimal or no_augassign: nodes.remove('augassign') self.node_handlers = {} for node in nodes: self.node_handlers[node] = getattr(self, "on_%s" % node) # to rationalize try/except try/finally for Python2.6 through Python3.3 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 'numpy.lib.index_tricks' in repr(val) or inspect.ismodule(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): """set node handler""" self.node_handlers[node] = 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.""" self.raise_exception(node, exc=NotImplementedError, msg="'%s' not supported" % (node.__class__.__name__)) 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 = '%s' % msg 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 = "at expr='%s'" % (self.expr) 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.""" self.expr = text try: out = ast.parse(text) except SyntaxError: self.raise_exception(None, msg='Syntax Error', expr=text) except: self.raise_exception(None, msg='Runtime Error', 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: return self.unimplemented(node) # 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 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() try: node = self.parse(expr) 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: exc = RuntimeError raise exc(errmsg) if show_errors: print(errmsg, file=self.err_writer) return 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: exc = RuntimeError raise exc(errmsg) if show_errors: print(errmsg, file=self.err_writer) return @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',) 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.""" self.retval = self.run(node.value) if self.retval is None: self.retval = ReturnedNone return 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.""" 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): 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_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.""" return node.n def on_str(self, node): # ('s',) """Return string.""" return node.s def on_name(self, node): # ('id', 'ctx') """Name node.""" ctx = node.ctx.__class__ if ctx in (ast.Param, ast.Del): return str(node.id) else: if node.id in self.symtable: return self.symtable[node.id] else: msg = "name '%s' is not defined" % node.id self.raise_exception(node, exc=NameError, msg=msg) def on_nameconstant(self, node): """True, False, or None""" 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 = "invalid symbol name (reserved word?) %s" % 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 = "cannot assign to attribute %s" % 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 = "no attribute '%s' for %s" % (node.attr, self.run(node.value)) self.raise_exception(node, exc=AttributeError, msg=msg) def on_assign(self, node): # ('targets', 'value') """Simple assignment.""" val = self.run(node.value) for tnode in node.targets: self.node_assign(tnode, val) return 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] else: msg = "subscript with unknown context" self.raise_exception(node, msg=msg) 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 n in node.values[1:]: val = op2func(node.op)(val, self.run(n)) 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, e_tback = 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 = "%s: %s" % (msg, msg2) self.raise_exception(None, exc=out.__class__, msg=msg, expr='') def on_call(self, node): """Function execution.""" # ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too) func = self.run(node.func) if not hasattr(func, '__call__') and not isinstance(func, type): msg = "'%s' is not callable!!" % (func) 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 = "keyword error in function call '%s'" % (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, msg="keyword argument repeated: %s" % key.arg, exc=SyntaxError) else: keywords[key.arg] = self.run(key.value) kwargs = getattr(node, 'kwargs', None) if kwargs is not None: keywords.update(self.run(kwargs)) try: return func(*args, **keywords) except Exception as ex: func_name = getattr(func, '__name__', str(func)) self.raise_exception( node, msg="Error running function call '%s' with args %s and " "kwargs %s: %s" % (func_name, args, keywords, ex)) 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 = "invalid function name (reserved word?) %s" % node.name self.raise_exception(node, exc=NameError, msg=errmsg) offset = len(node.args.args) - len(node.args.defaults) for idef, defnode in enumerate(node.args.defaults): defval = self.run(defnode) keyval = self.run(node.args.args[idef+offset]) kwargs.append((keyval, defval)) args = [tnode.arg for tnode in node.args.args[:offset]] doc = None nb0 = node.body[0] if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str): 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) 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 = "%s%s" % (sig, ', '.join(self.argnames)) if self.vararg is not None: sig = "%s, *%s" % (sig, self.vararg) if len(self.kwargs) > 0: if len(sig) > 0: sig = "%s, " % sig _kw = ["%s=%s" % (k, v) for k, v in self.kwargs] sig = "%s%s" % (sig, ', '.join(_kw)) if self.varkws is not None: sig = "%s, **%s" % (sig, self.varkws) sig = "" % (self.name, sig) if self.__doc__ is not None: sig = "%s\n %s" % (sig, self.__doc__) return sig def __call__(self, *args, **kwargs): """TODO: docstring in public method.""" 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 = "%s() takes at least %i arguments, got %i" self.raise_exc(None, exc=TypeError, msg=msg % (self.name, nargs_expected, nargs)) # check for multiple values for named argument if len(self.argnames) > 0 and kwargs is not None: msg = "multiple values for keyword argument '%s' in Procedure %s" for targ in self.argnames: if targ in kwargs: self.raise_exc(None, exc=TypeError, msg=msg % (targ, self.name), lineno=self.lineno) # check more args given than expected, varargs not given if nargs != nargs_expected: msg = None if nargs < nargs_expected: msg = 'not enough arguments for Procedure %s()' % self.name msg = '%s (expected %i, got %i)' % (msg, nargs_expected, 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 = 'too many arguments for %s() expected at most %i, got %i' msg = msg % (self.name, len(self.kwargs)+nargs_expected, 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 = 'extra keyword arguments for Procedure %s (%s)' msg = msg % (self.name, ','.join(list(kwargs.keys()))) self.raise_exc(None, msg=msg, exc=TypeError, lineno=self.lineno) except (ValueError, LookupError, TypeError, NameError, AttributeError): msg = 'incorrect arguments for Procedure %s' % self.name self.raise_exc(None, msg=msg, lineno=self.lineno) save_symtable = self.__asteval__.symtable.copy() self.__asteval__.symtable.update(symlocals) self.__asteval__.retval = None 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 symlocals = None return retval asteval-0.9.25/asteval/astutils.py000066400000000000000000000402151406434742100171360ustar00rootroot00000000000000""" 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 HAS_NUMPY = False numpy = None try: import numpy ndarr = numpy.ndarray HAS_NUMPY = True numpy_version = numpy.version.version.split('.', 2) except ImportError: pass MAX_EXPONENT = 10000 MAX_STR_LEN = 2 << 17 # 256KiB MAX_SHIFT = 1000 MAX_OPEN_BUFFER = 2 << 17 RESERVED_WORDS = ('and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'True', 'False', 'None', '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') # 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') FROM_NUMPY = ('Inf', 'NAN', 'abs', 'add', 'alen', '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', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'bool', 'broadcast', 'broadcast_arrays', 'byte', 'c_', 'cdouble', 'ceil', 'cfloat', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'complex', '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', 'fill_diagonal', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'fliplr', 'flipud', 'float', 'float32', 'float64', 'float_', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'fv', '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', 'int', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'int_asbuffer', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'ipmt', 'irr', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'long', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'mafromtxt', 'mask_indices', 'mat', 'matrix', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'negative', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'nper', 'npv', 'number', 'obj2sctype', 'ogrid', 'ones', 'ones_like', 'outer', 'packbits', 'percentile', 'pi', 'piecewise', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'ppmt', 'prod', 'product', 'ptp', 'put', 'putmask', 'pv', 'r_', 'rad2deg', 'radians', 'rank', 'rate', 'ravel', 'real', 'real_if_close', 'reciprocal', 'record', 'remainder', 'repeat', 'reshape', 'resize', 'restoredot', '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', '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', 'uint0', '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', 'fft', 'linalg', 'polynomial', 'random') NUMPY_RENAMES = {'ln': 'log', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'acosh': 'arccosh', 'asinh': 'arcsinh'} def _open(filename, mode='r', buffering=-1): """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) def _type(obj, *varargs, **varkws): """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: if 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(a, b): """safe version of multiply""" if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN: raise RuntimeError(f"String length exceeded, max string length is {MAX_STR_LEN}") return a * b def safe_add(a, b): """safe version of add""" if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN: raise RuntimeError(f"String length exceeded, max string length is {MAX_STR_LEN}") return a + b def safe_lshift(a, b): """safe version of lshift""" if isinstance(b, numbers.Number): if b > MAX_SHIFT: raise RuntimeError(f"Invalid left shift, max left shift is {MAX_SHIFT}") elif HAS_NUMPY: if isinstance(b, numpy.ndarray): if numpy.nanmax(b) > MAX_SHIFT: raise RuntimeError(f"Invalid left shift, max left shift is {MAX_SHIFT}") return a << b 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.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(op): """Return function for operator nodes.""" return OPERATORS[op.__class__] class Empty: """Empty class.""" def __init__(self): """TODO: docstring in public method.""" pass def __nonzero__(self): """TODO: docstring in magic method.""" return False 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 = [" %s" % self.expr] if col_offset > 0: out.append(" %s^^^" % ((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.ctx.__class__ == ast.Load and node.id not in self.names: self.names.append(node.id) ast.NodeVisitor.generic_visit(self, node) builtins = __builtins__ if not isinstance(builtins, dict): builtins = builtins.__dict__ def get_ast_names(astnode): """Return symbol Names from an AST node.""" finder = NameFinder() finder.generic_visit(astnode) return finder.names def make_symbol_table(use_numpy=True, **kws): """Create a default symboltable, taking dict of user-defined symbols. Arguments --------- numpy : bool, optional whether to include symbols from numpy kws : optional additional symbol name, value pairs to include in symbol table Returns -------- symbol_table : dict a symbol table that can be used in `asteval.Interpereter` """ symtable = {} for sym in FROM_PY: if sym in builtins: symtable[sym] = builtins[sym] for sym in FROM_MATH: if hasattr(math, sym): symtable[sym] = getattr(math, sym) if HAS_NUMPY and use_numpy: # aliases deprecated in NumPy v1.20.0 deprecated = ['str', 'bool', 'int', 'float', 'complex', 'pv', 'rate', 'pmt', 'ppmt', 'npv', 'nper', 'long', 'mirr', 'fv', 'irr', 'ipmt'] for sym in FROM_NUMPY: if (int(numpy_version[0]) == 1 and int(numpy_version[1]) >= 20 and sym in deprecated): continue if hasattr(numpy, sym): symtable[sym] = getattr(numpy, sym) for name, sym in NUMPY_RENAMES.items(): if hasattr(numpy, sym): symtable[name] = getattr(numpy, sym) symtable.update(LOCALFUNCS) symtable.update(kws) return symtable asteval-0.9.25/doc/000077500000000000000000000000001406434742100140205ustar00rootroot00000000000000asteval-0.9.25/doc/Makefile000066400000000000000000000063051406434742100154640ustar00rootroot00000000000000# 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.25/doc/_static/000077500000000000000000000000001406434742100154465ustar00rootroot00000000000000asteval-0.9.25/doc/_static/empty000066400000000000000000000000001406434742100165150ustar00rootroot00000000000000asteval-0.9.25/doc/_templates/000077500000000000000000000000001406434742100161555ustar00rootroot00000000000000asteval-0.9.25/doc/_templates/indexsidebar.html000066400000000000000000000004521406434742100215050ustar00rootroot00000000000000

Downloads

Current version: {{ release }}

Downloads: PyPI (Python.org)

try pip install asteval

Development version:
    github.com


asteval-0.9.25/doc/api.rst000066400000000000000000000113021406434742100153200ustar00rootroot00000000000000.. _asteval_api: ======================== asteval reference ======================== .. _numpy: http://docs.scipy.org/doc/numpy .. 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 tesing 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. By default, the interpreter will support many Python language constructs, including * advanced slicing: ``a[::-1], array[-3:, :, ::2]`` * if-elif-else conditionals * for loops, with ``else`` * while loops, with ``else`` * try-except-finally blocks * function definitions * augmented assignments: ``x += 1`` * if-expressions: ``x = a if TEST else b`` * list comprehension: ``out = [sqrt(i) for i in values]`` with the exception of slicing, each of these features can be turned off with the appropriate ``no_XXX`` option. To turn off all these optional constructs, and create a simple expression calculator, use ``minimal=True``. Many Python syntax elements are not supported at all, including: Import, Exec, Lambda, Class, Global, Generators, Yield, Decorators In addition, many actions that are known to be unsafe (such as inspecting objects to get at their base classes) are also not allowed. 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]]) 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 .. method:: __call__(expression[, lineno=0[, show_errors=True]]) 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. A dictionary with symbol names as keys, and object values (data and functions). For full control of the symbol table, you can simply access the :attr:`symtable` object, inserting, replacing, or removing symbols to alter what symbols are known to your interpreter. You can also access the :attr:`symtable` to retrieve results. .. 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. 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.25/doc/basics.rst000066400000000000000000000135021406434742100160170ustar00rootroot00000000000000================ 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 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, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, True, False, None, eval, execfile, __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, type, 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: http://docs.scipy.org/doc/numpy If available, a very large number (~400) additional symbols are imported from `numpy`_. conditionals and loops ========================== If-then-else blocks, for-loops (including the optional *else* block) and while loops (also including optional *else* block) 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 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.25/doc/conf.py000066400000000000000000000151701406434742100153230ustar00rootroot00000000000000# -*- 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.25/doc/index.rst000066400000000000000000000062361406434742100156700ustar00rootroot00000000000000.. asteval documentation master file, ASTEVAL: Minimal Python AST Evaluator ================================================ .. _numpy: http://docs.scipy.org/doc/numpy 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. 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. Variable and function symbol names are held in a simple symbol table - a single dictionary - giving a flat namespace. 2. creating classes is not allowed. 3. importing modules is not allowed. 4. f-strings, function decorators, generators, yield, type hint, and `lambda` are not supported. 5. Many builtin functions (:py:func:`eval`, :py:func:`execfile`, :py:func:`getattr`, :py:func:`hasattr`, :py:func:`setattr`, and :py:func:`delattr`) are not allowed. 6. Accessing several private 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. 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.25/doc/installation.rst000066400000000000000000000033571406434742100172630ustar00rootroot00000000000000==================================== Downloading and Installation ==================================== .. _numpy: http://docs.scipy.org/doc/numpy .. _github: http://github.com/newville/asteval .. _PyPI: http://pypi.python.org/pypi/asteval/ Requirements ~~~~~~~~~~~~~~~ Asteval is a pure python module with no required dependencies outside of the standard library. Asteval will make use of the `numpy`_ module if available. The test suite requires the `pytest` module. The latest stable version of asteval is |release|. Versions 0.9.21 and later support and are tested with Python 3.6 through 3.9. Python 3.6 will be supported until at least its official end of life (December 2021). No released version supports Python 3.10 yet. Versions 0.9.18, 0.9.19, and 0.9.20 supported and were tested with Python 3.5 through 3.8. Version 0.9.17 was the last version to support Python 2.7. 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 http://github.com/newville/asteval.git Installation ~~~~~~~~~~~~~~~~~ Installation from source on any platform is:: python setup.py install License ~~~~~~~~~~~~~ The ASTEVAL code is distribution under the following license: .. literalinclude:: ../LICENSE asteval-0.9.25/doc/motivation.rst000066400000000000000000000206101406434742100167420ustar00rootroot00000000000000.. _lmfit: http://github.com/lmfit/lmfit-py .. _xraylarch: http://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 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 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. * create classes or modules. * access to Python's :py:func:`eval`, :py:func:`execfile`, :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 seg-fault the Python. It should be noted that asteval will typically expose numpy ufuncs from the numpy module, and several of these can seg-fault Python without too much trouble. If you're paranoid about safe user input that can never cause a segmentation fault, you may want to consider disabling the use of numpy entirely. 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. 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. As a simple 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. In short, runtime cannot be determined lexically. This double 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, in Python's C C-code (no doubt calling the `pow()` function) called by the Python interpreter itself. That call will not return to the Python interpreter or allow other threads to run until that call is done. That means that from within a single process, there is not a foolproof way to tell `asteval` (or really, even Python) when a calculation has taken too long. The most reliable way to limit run time is to have a second process watching the execution time of the asteval process and interrupt 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(...) As an addition security concern, 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 be supported. This doesn't really 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 are many ways that asteval could be considered part of an un-safe programming environment. Recommendations for how to improve this situation would be greatly appreciated. asteval-0.9.25/requirements.txt000066400000000000000000000001421406434742100165340ustar00rootroot00000000000000## ## pip requirements file. To install dependencies, use ## ## pip install -r requirements.txt asteval-0.9.25/setup.cfg000066400000000000000000000002401406434742100150700ustar00rootroot00000000000000[versioneer] VCS = git style = pep440 versionfile_source = asteval/_version.py versionfile_build = asteval/_version.py tag_prefix = parentdir_prefix = asteval- asteval-0.9.25/setup.py000066400000000000000000000023701406434742100147670ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup 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. """ setup(name='asteval', use_scm_version=True, setup_requires=['setuptools_scm'], author='Matthew Newville', author_email='newville@cars.uchicago.edu', url='http://github.com/newville/asteval', license='OSI Approved :: MIT License', python_requires='>=3.6', description="Safe, minimalistic evaluator of python expression using ast module", long_description=long_description, packages=['asteval'], tests_require=['pytest'], classifiers=['Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) asteval-0.9.25/tests/000077500000000000000000000000001406434742100144155ustar00rootroot00000000000000asteval-0.9.25/tests/test_asteval.py000066400000000000000000001062321406434742100174710ustar00rootroot00000000000000#!/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 class TestCase(unittest.TestCase): """testing of asteval""" def setUp(self): self.interp = Interpreter() self.symtable = self.interp.symtable self.set_stdout() self.set_stderr() def set_stdout(self): self.stdout = NamedTemporaryFile('w', delete=False, prefix='astevaltest') self.interp.writer = self.stdout def read_stdout(self): 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): self.stderr = NamedTemporaryFile('w', delete=False, prefix='astevaltest_stderr') self.interp.err_writer = self.stderr def read_stderr(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_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) # 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'): 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]) 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("10**10000") self.check_error(None) self.interp("10**10001") self.check_error('RuntimeError') 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', 'Lambda') # 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 self.interp( "x = ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((1))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))") if version_info.minor > 8: self.isvalue('x', 1) self.check_error(None) else: self.check_error('MemoryError') # 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_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_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, 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) o1 = self.interp("sarr < 4.3") assert(np.all(o1 == (sarr < 4.3))) o1 = self.interp("sarr == 4") assert(np.all(o1 == (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()") class TestCase2(unittest.TestCase): def test_stringio(self): """ test using stringio for output/errors """ out = StringIO() err = StringIO() intrep = Interpreter(writer=out, err_writer=err) intrep("print('out')") self.assertEqual(out.getvalue(), 'out\n') if __name__ == '__main__': pytest.main(['-v', '-x', '-s'])