asteval reference

The asteval module has a pretty simple interface, providing an 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: valid_symbol_name() is useful for tesing the validity of symbol names, and make_symbol_table() is useful for creating symbol tables that may be pre-loaded with custom symbols and functions.

The Interpreter class

class asteval.Interpreter(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=30)

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 assigments (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.
  • max_time (float) – deprecated. max run time in seconds (see Note 2) [30.0]

Notes

  1. setting minimal=True is equivalent to setting all no_*** options to True.
  2. max_time is not reliable and support may be dropped soon.

By default, the symbol table will be created with make_symbol_table() that will include several standard python builtin functions, several functions from the 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 sys.stdout. The default is, of course, to send output to sys.stdout. Similarly, err_writer will be used for output that will otherwise be sent to 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.

asteval.eval(expression[, lineno=0[, show_errors=True]])

evaluate the expression, returning the result.

Parameters:
  • expression (string) – code to evaluate.
  • lineno (int) – line number (for error messages).
  • show_errors (bool) – whether to print error messages or leave them in the errors list.
asteval.__call__(expression[, lineno=0[, show_errors=True]])

same as eval(). That is:

>>> from asteval import Interpreter
>>> a = Interpreter()
>>> a('x = 1')

instead of:

>>> a.eval('x = 1')
asteval.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 symtable object, inserting, replacing, or removing symbols to alter what symbols are known to your interpreter. You can also access the symtable to retrieve results.

asteval.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.

asteval.error_msg

the most recent error message.

Utility Functions

asteval.valid_symbol_name(name)

Determine whether the input symbol name is a valid name.

Parameters:name (str) – name to check for validity.
Returns:valid – whether name is a a valid symbol name
Return type:bool

This checks for Python reserved words and that the name matches the regular expression [a-zA-Z_][a-zA-Z0-9_]

asteval.make_symbol_table(use_numpy=True, **kws)

Create a default symboltable, taking dict of user-defined symbols.

Parameters:
  • numpy (bool, optional) – whether to include symbols from numpy
  • kws (optional) – additional symbol name, value pairs to include in symbol table
Returns:

symbol_table – a symbol table that can be used in asteval.Interpereter

Return type:

dict

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.