Skip to content

Commit

Permalink
Also filter out empty text segments
Browse files Browse the repository at this point in the history
  • Loading branch information
ncoghlan committed Sep 1, 2024
1 parent 22b9e48 commit 877fe7d
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions peps/pep-0501.rst
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,12 @@ following behaviour:
text._raw = raw
return text
@staticmethod
def merge(text_segments:Sequence[TemplateLiteralText]) -> TemplateLiteralText:
if len(text_segments) == 1:
return text_segments[0]
return TemplateLiteralText("".join(t._raw for t in text_segments))
@property
def raw(self) -> str:
return self._raw
Expand All @@ -349,10 +355,6 @@ following behaviour:
return TemplateLiteralText(self._raw * factor)
__rmul__ = __mul__
@staticmethod
def merge(text_segments:Sequence[TemplateLiteralText]) -> TemplateLiteralText:
return TemplateLiteralText("".join(t._raw for t in text_segments))
class TemplateLiteralField(NamedTuple):
# This is mostly a renamed version of the InterpolationConcrete type in PEP 750
# However:
Expand Down Expand Up @@ -391,11 +393,12 @@ following behaviour:
self = super().__new__(cls)
self._raw_template = raw_template
# Check if there are any adjacent text segments that need merging
# or any empty text segments that need discarding
text_expected = True
needs_merge = False
for segment in segments:
if isinstance(segment, TemplateLiteralText):
if not text_expected:
if not text_expected or not segment:
needs_merge = True
break
text_expected = False
Expand All @@ -404,13 +407,14 @@ following behaviour:
if not needs_merge:
self._segments = segments
return self
# Ensure any consecutive runs of text fields are merged together
# Merge consecutive runs of text fields and drop any empty text fields
merged_segments:list[TemplateLiteralText|TemplateLiteralField] = []
pending_merge:list[TemplateLiteralText] = []
for segment in segments:
match segment:
case TemplateLiteralText() as text_segment:
pending_merge.append(text_segment)
if text_segment:
pending_merge.append(text_segment)
case TemplateLiteralField():
if pending_merge:
merged_segments.append(TemplateLiteralText.merge(pending_merge))
Expand Down

0 comments on commit 877fe7d

Please sign in to comment.