The Numeric String Parser

For the particularly curious, here is the Numeric String Parser used by MathBlock. There are some more functions, mainly internal parsing helpers, that are not included here.

The Numeric String Parser is powered by PyParsing.

class ya_tagscript.blocks.math.math_block.NumericStringParser[source]

This is the grammar used by this class:

The consts values are all caseless, so pi, PI, etc., all work.

consts    ::= E | PI | π | TAU | τ
float_num ::= [+-]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?
ident     ::= [a-zA-Z][a-zA-Z0-9_$]*
addop     ::= '+' | '-'
multop    ::= '*' | '/' | '%'
iop       ::= '+=' | '-=' | '*=' | '/='
expop     ::= '^'
atom      ::= consts | float_num | ident | fn_call | '(' expr ')'
factor    ::= atom [ expop factor ]*
term      ::= factor [ multop factor ]*
expr      ::= term [ addop term ]*
expr_list ::= expr (',' expr)*
fn_call   ::= ident '(' expr_list ')'
final     ::= expr [ iop expr ]*
EPSILON: float = 1e-12

Maximum precision used by the parser

eval(num_string: str, parse_all: bool = True) int | float[source]

Evaluates the num_string mathematical expression

Parameters:
  • num_string (str) – The mathematical expression string to parse and evaluate

  • parse_all (bool) – Whether the entire string has to match the grammar (default: True)

Returns:

The calculated result

Return type:

int | float

Raises:
  • pyparsing.ParseException – Raised if parse_all is True but num_string did not fully match the grammar

  • ValueError – Raised if an invalid identifier is used that is not a supported constant, operator, or function