From 780772ec2d14950eb3fde537182e2afdffec9ac0 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Thu, 13 Dec 2018 09:29:44 +0100 Subject: [PATCH] Feat(API): Expression.from_str tries to build a token when it's possible --- mapytex/calculus/API/expression.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/mapytex/calculus/API/expression.py b/mapytex/calculus/API/expression.py index abb0044..315b303 100644 --- a/mapytex/calculus/API/expression.py +++ b/mapytex/calculus/API/expression.py @@ -41,14 +41,38 @@ class Expression(object): self._ancestor = ancestor @classmethod - def from_str(cls, string): + def from_str(cls, string, typing=True): """ Initiate the expression from a string :param string: String to parse to generate the Expression :returns: the expression + :example: + >>> e = Expression.from_str("2 + 3 * 4") + >>> e + + >>> e = Expression.from_str("2/3") + >>> e + + >>> e = Expression.from_str("2x + 1") + >>> e + + >>> e = Expression.from_str("2x + 1 + 5x^2") + >>> e + + >>> e = Expression.from_str("2x + 1 + 5x") + >>> e + + """ t = Tree.from_str(string) + if typing: + tt = cls(t)._typing() + try: + return factory(tt) + except TypeError as e: + return cls(t) + return cls(t) @classmethod @@ -173,7 +197,7 @@ class Expression(object): """ Build a copy of self with as much typing as possible :example: - >>> e = Expression.from_str("2x") + >>> e = Expression.from_str("2x", typing=False) >>> print(e._tree.map_on_leaf(type)) * > @@ -185,7 +209,7 @@ class Expression(object): >>> print(type(typed_e._tree)) - >>> e = Expression.from_str("2x+3+4/5") + >>> e = Expression.from_str("2x+3+4/5", typing=False) >>> print(e._tree.map_on_leaf(type)) + > +