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
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.
- 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=None, readonly_symbols=None, builtins_readonly=False)¶
create an asteval Interpreter: a restricted, simplified interpreter of mathematical expressions using Python syntax.
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
setting minimal=True is equivalent to setting all no_*** options to True.
By default, the symbol table will be created with
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.
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
will be used for output that will otherwise be sent to
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
a[::-1], array[-3:, :, ::2]
for loops, with
while loops, with
x += 1
x = a if TEST else b
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
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.
- asteval.__call__(expression[, lineno=0[, show_errors=True]])¶
eval(). That is:
>>> from asteval import Interpreter >>> a = Interpreter() >>> a('x = 1')
>>> a.eval('x = 1')
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
symtableobject, inserting, replacing, or removing symbols to alter what symbols are known to your interpreter. You can also access the
symtableto retrieve results.
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.
the most recent error message.
Determine whether the input symbol name is a valid name.
name (str) – name to check for validity.
valid – whether name is a a valid symbol name
- Return type
This checks for Python reserved words and that the name matches the regular expression
- asteval.make_symbol_table(use_numpy=True, **kws)¶
Create a default symboltable, taking dict of user-defined symbols.
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