asteval reference

The asteval module provides an Interpreter class, which creates an interpreter. There is also a convenience function valid_symbol_name()

class asteval.Interpreter(symtable=None[, writer=None[, use_numpy=True]])

create an asteval interpreter.

Parameters:
  • symtable (None or dict.) -- a Symbol table (if None, one will be created).
  • writer (file-like.) -- callable file-like object where standard output will be sent.
  • use_numpy (boolean (True / False)) -- whether to use functions from numpy.

The symbol table will be loaded with several built in functions, several functions from the math module and, if available and requested, several functions from numpy. This will happen even for a symbol table explicitly provided.

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.

The use_numpy argument can be used to control whether functions from numpy are loaded into the symbol table.

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 one can do:

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

asteval.valid_symbol_name(name)

determines whether the input symbol name is a valid name

This checks for reserved words, and that the name matches the regular expression [a-zA-Z_][a-zA-Z0-9_] :param name: symbol name to test :return True if valid, False otherwise