Number are now int or Decimal when an expression is parsed

This commit is contained in:
Bertrand Benjamin 2018-01-28 18:54:30 +03:00
parent 251ec6c83b
commit a916035260

View File

@ -11,6 +11,7 @@ Converting a string with coroutines
"""
from functools import partial
from decimal import Decimal
from .coroutine import *
__all__ = ["str2", ]
@ -158,7 +159,7 @@ def lookfor(condition, replace = lambda x:''.join(x)):
else:
if c is not None:
acc.append(c)
found = condition(''.join(acc))
found = condition(''.join([str(i) for i in acc]))
if found == "maybe":
ans = "maybe"
elif found:
@ -322,14 +323,14 @@ def lookforNumbers(target):
... str2list.send(i)
>>> a = str2list.throw(STOOOP)
>>> print(a)
['12', '+', '1234', '*', '67']
[12, '+', 1234, '*', 67]
>>> str2list = lookforNumbers(list_sink)
>>> for i in "1.2+12.34*67":
... str2list.send(i)
>>> a = str2list.throw(STOOOP)
>>> print(a)
['1.2', '+', '12.34', '*', '67']
[Decimal('1.2'), '+', Decimal('12.34'), '*', 67]
>>> str2list = lookforNumbers(list_sink)
>>> for i in "12.3.4*67":
@ -368,7 +369,7 @@ def lookforNumbers(target):
current += tok
else:
if current:
target_.send(current)
target_.send(typifiy_numbers(current))
current = ""
target_.send(tok)
else:
@ -376,9 +377,16 @@ def lookforNumbers(target):
except STOOOP as err:
if current:
target_.send(current)
target_.send(typifiy_numbers(current))
yield target_.throw(err)
def typifiy_numbers(number):
""" Transform a str number into a integer or a decimal """
try:
return int(number)
except ValueError:
return Decimal(number)
@coroutine
def pparser(target):
""" Parenthesis parser sink
@ -447,15 +455,15 @@ def str2(sink):
>>> exp = "12+3*4"
>>> t = str2nestedlist(exp)
>>> print(t)
['12', '+', '3', '*', '4']
[12, '+', 3, '*', 4]
>>> exp = "12*3+4"
>>> t = str2nestedlist(exp)
>>> print(t)
['12', '*', '3', '+', '4']
[12, '*', 3, '+', 4]
>>> exp = "12*(3+4)"
>>> t = str2nestedlist(exp)
>>> print(t)
['12', '*', ['3', '+', '4']]
[12, '*', [3, '+', 4]]
>>> from .tree import MutableTree
>>> str2tree = str2(MutableTree.sink)