Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions src/tstrings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import sys
from dataclasses import dataclass
from itertools import zip_longest
from typing import TYPE_CHECKING, Literal, NoReturn, cast
from typing import TYPE_CHECKING, Literal, NoReturn, Union, cast

if TYPE_CHECKING:
from collections.abc import Iterator
Expand Down Expand Up @@ -42,7 +42,9 @@
if sys.version_info >= (3, 10):
dataclass_extra_args = {"slots": True}
else:
dataclass_extra_args = {}
dataclass_extra_args: dict[str, bool] = {}

Conversion = Union[Literal["s", "r", "a"], None]


@dataclass(frozen=True, eq=False, **dataclass_extra_args)
Expand All @@ -54,7 +56,7 @@ class Interpolation:

value: object
expression: str
conversion: Literal["a", "r", "s"] | None = None
conversion: Conversion = None
format_spec: str = ""

def __eq__(self, value: object) -> bool:
Expand Down Expand Up @@ -93,7 +95,7 @@ def values(self) -> tuple[object, ...]:
"""
return tuple(interp.value for interp in self.interpolations)

def __iter__(self) -> Iterator[str | Interpolation]:
def __iter__(self) -> Iterator[Union[str, Interpolation]]:
"""Iterate over the string parts and interpolations in the template.

These may appear in any order. Empty strings will not be included.
Expand Down Expand Up @@ -207,16 +209,13 @@ def t(template_string: str, /) -> Template:
raise SyntaxError("f-string: cannot specify both conversion and '='")

# If a format spec is present, conversion becomes 's'. Otherwise, 'r'.
conv_char: Literal["a", "r", "s"] | None = (
"s" if groups["format_spec"] else "r"
)
conversion: Conversion = "s" if groups["format_spec"] else "r"
expression_to_eval = expr_for_eval
else:
conv_char = (
cast(Literal["a", "r", "s"], groups["conversion"][1])
if groups["conversion"]
else None
)
if groups["conversion"]:
conversion = cast("Conversion", groups["conversion"][1])
else:
conversion = None
expression_to_eval = groups["expression"]

fmt_spec = groups["format_spec"][1:] if groups["format_spec"] else ""
Expand All @@ -238,7 +237,7 @@ def t(template_string: str, /) -> Template:
Interpolation(
value=value,
expression=expression_to_eval,
conversion=conv_char,
conversion=conversion,
format_spec=fmt_spec,
)
)
Expand Down