Skip to content

Commit dcec451

Browse files
committed
rbnf: store divisor and substitutions in Rule to avoid recomputation
1 parent 0927acc commit dcec451

1 file changed

Lines changed: 15 additions & 22 deletions

File tree

babel/rbnf.py

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,17 @@ def _parse_reference(string):
191191
return INTERNAL_REF, "" # defaults to this
192192

193193

194+
def compute_divisor(value, radix):
195+
# Compute the highest exponent of radix less than or equal to the rule's base
196+
if isinstance(value, int):
197+
if value == 0:
198+
return 1
199+
exp = decimal.Decimal(value).ln() / decimal.Decimal(radix).ln()
200+
return int(radix ** math.floor(exp))
201+
else:
202+
return None
203+
204+
194205
class RuleBasedNumberFormat(object):
195206
"""
196207
RuleBasedNumberFormat's behavior consists of one or more rule sets
@@ -638,15 +649,16 @@ def __init__(self, value, text, radix=None):
638649
"""
639650
divisor : iterator of literal, back_sub, fwd_sub, lit_exact elements parsed from rule
640651
"""
652+
self.radix = int(radix or 10)
641653
if value in self.specials:
642654
self.value = value
643655
else:
644656
self.value = int(value)
645657

658+
self.divisor = compute_divisor(self.value, self.radix)
646659
self.text = text
647-
self.radix = int(radix or 10)
648-
649-
self._parse(text)
660+
self.tokens = list(tokenize(text))
661+
self.substitutions = len([t for t in self.tokens if t.type in REFERENCE_TOKENS])
650662

651663
def apply(self, number, context):
652664
"""
@@ -694,25 +706,6 @@ def apply(self, number, context):
694706

695707
return ''.join(res)
696708

697-
@property
698-
def divisor(self):
699-
"""it is highest exponent of radix less then or equal to the rules's base"""
700-
if isinstance(self.value, int):
701-
if self.value == 0:
702-
return 1
703-
exp = decimal.Decimal(self.value).ln() / decimal.Decimal(self.radix).ln()
704-
return int(self.radix ** math.floor(exp))
705-
706-
@property
707-
def substitutions(self):
708-
return len([t for t in self.tokens if t.type in REFERENCE_TOKENS])
709-
710-
def _parse(self, text):
711-
try:
712-
self.tokens = [t for t in tokenize(text)]
713-
except ValueError:
714-
raise TokenizationError(text)
715-
716709
def __repr__(self):
717710
return 'Rule %s (%s) - %s\n%s\n' % (
718711
self.value, self.text,

0 commit comments

Comments
 (0)