cache parsed Formatter functions

This commit is contained in:
Mike Fährmann 2021-06-22 19:39:38 +02:00
parent a416e54765
commit befe635022
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88

View File

@ -559,6 +559,7 @@ class Formatter():
Replaces all occurrences of <old> with <new> Replaces all occurrences of <old> with <new>
Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r") Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r")
""" """
CACHE = {}
CONVERSIONS = { CONVERSIONS = {
"l": str.lower, "l": str.lower,
"u": str.upper, "u": str.upper,
@ -575,20 +576,27 @@ class Formatter():
def __init__(self, format_string, default=None): def __init__(self, format_string, default=None):
self.default = default self.default = default
key = (format_string, default)
try:
self.result, self.fields = self.CACHE[key]
except KeyError:
self.result = [] self.result = []
self.fields = [] self.fields = []
for literal_text, field_name, format_spec, conversion in \ for literal_text, field_name, format_spec, conv in \
_string.formatter_parser(format_string): _string.formatter_parser(format_string):
if literal_text: if literal_text:
self.result.append(literal_text) self.result.append(literal_text)
if field_name: if field_name:
self.fields.append(( self.fields.append((
len(self.result), len(self.result),
self._field_access(field_name, format_spec, conversion), self._field_access(field_name, format_spec, conv),
)) ))
self.result.append("") self.result.append("")
self.CACHE[key] = (self.result, self.fields)
if len(self.result) == 1: if len(self.result) == 1:
if self.fields: if self.fields:
self.format_map = self.fields[0][1] self.format_map = self.fields[0][1]