Skip to content

Commit 2da3e63

Browse files
committed
Make TokenList.value a property not an attribute.
The fact that a new value was being computed each time TokenList.group_tokens() was called caused supra-linear runtime when token grouping was enabled. Address by making TokenList.value a dynamically-computed property rather than a static attribute.
1 parent 8d66db3 commit 2da3e63

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

sqlparse/sql.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ class TokenBase:
4848
def __init__(self):
4949
self.parent = None
5050

51+
def __str__(self):
52+
return self.value
53+
5154
# Pending tokenlist __len__ bug fix
5255
# def __len__(self):
5356
# return len(self.value)
@@ -155,9 +158,6 @@ def __init__(self, ttype, value):
155158
self.is_newline = self.ttype in T.Newline
156159
self.normalized = value.upper() if self.is_keyword else value
157160

158-
def __str__(self):
159-
return self.value
160-
161161
def _get_repr_name(self):
162162
return str(self.ttype).split('.')[-1]
163163

@@ -169,11 +169,11 @@ def flatten(self):
169169
class TokenList(TokenBase):
170170
"""A group of tokens.
171171
172-
It has two additional instance attributes, ``value``, which is the value of
173-
the token list, and ``tokens``, which holds a list of child-tokens.
172+
It has an additional instance attribute ``tokens`` which holds a
173+
list of child-tokens.
174174
"""
175175

176-
__slots__ = ('tokens', 'value')
176+
__slots__ = 'tokens'
177177

178178
is_group = True
179179
ttype = None
@@ -184,10 +184,10 @@ class TokenList(TokenBase):
184184
def __init__(self, tokens=None):
185185
super().__init__()
186186
self.tokens = tokens or []
187-
self.value = str(self)
188187
[setattr(token, 'parent', self) for token in self.tokens]
189188

190-
def __str__(self):
189+
@property
190+
def value(self):
191191
return ''.join(token.value for token in self.flatten())
192192

193193
@property
@@ -352,7 +352,6 @@ def group_tokens(self, grp_cls, start, end, include_end=True,
352352
grp = start
353353
grp.tokens.extend(subtokens)
354354
del self.tokens[start_idx + 1:end_idx]
355-
grp.value = str(start)
356355
else:
357356
subtokens = self.tokens[start_idx:end_idx]
358357
grp = grp_cls(subtokens)

0 commit comments

Comments
 (0)