Parsing input

Parsing Functions Reference

sympy.parsing.sympy_parser.parse_expr(s, local_dict=None, transformations=(<function auto_symbol at 0xffd9064>, <function auto_number at 0xffd910c>, <function factorial_notation at 0xffd909c>), global_dict=None, evaluate=True)[source]

Converts the string s to a SymPy expression, in local_dict

Parameters :

s : str

The string to parse.

local_dict : dict, optional

A dictionary of local variables to use when parsing.

global_dict : dict, optional

A dictionary of global variables. By default, this is initialized with from sympy import *; provide this parameter to override this behavior (for instance, to parse "Q & S").

transformations : tuple, optional

A tuple of transformation functions used to modify the tokens of the parsed expression before evaluation. The default transformations convert numeric literals into their SymPy equivalents, convert undefined variables into SymPy symbols, and allow the use of standard mathematical factorial notation (e.g. x!).

See also

stringify_expr, eval_expr, standard_transformations, implicit_multiplication_application

Examples

>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("1/2")
1/2
>>> type(_)
<class 'sympy.core.numbers.Half'>
>>> from sympy.parsing.sympy_parser import standard_transformations,\
... implicit_multiplication_application
>>> transformations = (standard_transformations +
...     (implicit_multiplication_application,))
>>> parse_expr("2x", transformations=transformations)
2*x
sympy.parsing.sympy_parser.stringify_expr(s, local_dict, global_dict, transformations)[source]

Converts the string s to Python code, in local_dict

Generally, parse_expr should be used.

sympy.parsing.sympy_parser.eval_expr(code, local_dict, global_dict)[source]

Evaluate Python code generated by stringify_expr.

Generally, parse_expr should be used.

sympy.parsing.sympy_tokenize.printtoken(type, token, srow_scol, erow_ecol, line)[source]
sympy.parsing.sympy_tokenize.tokenize(readline, tokeneater=<function printtoken at 0xffcc6bc>)[source]

The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize().

The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string.

The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens().

sympy.parsing.sympy_tokenize.untokenize(iterable)[source]

Transform tokens back into Python source code.

Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor.

Round-trip invariant for full input:
Untokenized source will match input source exactly

Round-trip invariant for limited intput:

# Output text will tokenize the back to the input
t1 = [tok[:2] for tok in generate_tokens(f.readline)]
newcode = untokenize(t1)
readline = iter(newcode.splitlines(1)).next
t2 = [tok[:2] for tok in generate_tokens(readline)]
if t1 != t2:
    raise ValueError("t1 should be equal to t2")
sympy.parsing.sympy_tokenize.generate_tokens(readline)[source]

The generate_tokens() generator requires one argment, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration:

readline = open(myfile).next    # Example of alternate readline

The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included.

sympy.parsing.sympy_tokenize.group(*choices)[source]
sympy.parsing.sympy_tokenize.any(*choices)[source]
sympy.parsing.sympy_tokenize.maybe(*choices)[source]
sympy.parsing.maxima.parse_maxima(str, globals=None, name_dict={})[source]
sympy.parsing.mathematica.mathematica(s)[source]

Parsing Exceptions Reference

class sympy.parsing.sympy_tokenize.TokenError[source]
class sympy.parsing.sympy_tokenize.StopTokenizing[source]

Parsing Transformations Reference

A transformation is a function that accepts the arguments tokens, local_dict, global_dict and returns a list of transformed tokens. They can be used by passing a list of functions to parse_expr() and are applied in the order given.

sympy.parsing.sympy_parser.standard_transformations = (<function auto_symbol at 0xffd9064>, <function auto_number at 0xffd910c>, <function factorial_notation at 0xffd909c>)

Standard transformations for parse_expr(). Inserts calls to Symbol, Integer, and other SymPy datatypes and allows the use of standard factorial notation (e.g. x!).

sympy.parsing.sympy_parser.split_symbols(tokens, local_dict, global_dict)

Splits symbol names for implicit multiplication.

Intended to let expressions like xyz be parsed as x*y*z. Does not split Greek character names, so theta will not become t*h*e*t*a. Generally this should be used with implicit_multiplication.

sympy.parsing.sympy_parser.split_symbols_custom(predicate)[source]

Creates a transformation that splits symbol names.

predicate should return True if the symbol name is to be split.

For instance, to retain the default behavior but avoid splitting certain symbol names, a predicate like this would work:

>>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
... standard_transformations, implicit_multiplication,
... split_symbols_custom)
>>> def can_split(symbol):
...     if symbol not in ('list', 'of', 'unsplittable', 'names'):
...             return _token_splittable(symbol)
...     return False
...
>>> transformation = split_symbols_custom(can_split)
>>> parse_expr('unsplittable', transformations=standard_transformations +
... (transformation, implicit_multiplication))
unsplittable
sympy.parsing.sympy_parser.implicit_multiplication(result, local_dict, global_dict)[source]

Makes the multiplication operator optional in most cases.

Use this before implicit_application(), otherwise expressions like sin 2x will be parsed as x * sin(2) rather than sin(2*x).

Example:

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication)
>>> transformations = standard_transformations + (implicit_multiplication,)
>>> parse_expr('3 x y', transformations=transformations)
3*x*y
sympy.parsing.sympy_parser.implicit_application(result, local_dict, global_dict)[source]

Makes parentheses optional in some cases for function calls.

Use this after implicit_multiplication(), otherwise expressions like sin 2x will be parsed as x * sin(2) rather than sin(2*x).

Example:

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_application)
>>> transformations = standard_transformations + (implicit_application,)
>>> parse_expr('cot z + csc z', transformations=transformations)
cot(z) + csc(z)
sympy.parsing.sympy_parser.function_exponentiation(tokens, local_dict, global_dict)[source]

Allows functions to be exponentiated, e.g. cos**2(x).

Example:

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, function_exponentiation)
>>> transformations = standard_transformations + (function_exponentiation,)
>>> parse_expr('sin**4(x)', transformations=transformations)
sin(x)**4
sympy.parsing.sympy_parser.implicit_multiplication_application(result, local_dict, global_dict)[source]

Allows a slightly relaxed syntax.

  • Parentheses for single-argument method calls are optional.
  • Multiplication is implicit.
  • Symbol names can be split (i.e. spaces are not needed between symbols).
  • Functions can be exponentiated.

Example:

>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication_application)
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
... transformations=(standard_transformations +
... (implicit_multiplication_application,)))
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
sympy.parsing.sympy_parser.rationalize(tokens, local_dict, global_dict)[source]

Converts floats into Rational. Run AFTER auto_number.

sympy.parsing.sympy_parser.convert_xor(tokens, local_dict, global_dict)[source]

Treats XOR, ^, as exponentiation, **.

These are included in :data:sympy.parsing.sympy_parser.standard_transformations and generally don’t need to be manually added by the user.

sympy.parsing.sympy_parser.factorial_notation(tokens, local_dict, global_dict)[source]

Allows standard notation for factorial.

sympy.parsing.sympy_parser.auto_symbol(tokens, local_dict, global_dict)[source]

Inserts calls to Symbol for undefined variables.

sympy.parsing.sympy_parser.auto_number(tokens, local_dict, global_dict)[source]

Converts numeric literals to use SymPy equivalents.

Complex numbers use I; integer literals use Integer, float literals use Float, and repeating decimals use Rational.

Table Of Contents

Previous topic

Timing Utilities

Next topic

Calculus

This Page