Skip to content

Add helpers to Interpolation for common string formatting cases #140056

@zahlman

Description

@zahlman

Feature or enhancement

Proposal:

It seems clear that the most common use cases for t-strings will involve formatters that produce a string (for example, sanitized SQL as described in the PEP), which will in turn typically involve creating strings representing each interpolated value. Further, the t-string design specifically allows for the interpolated values to use conversions and format specifiers, following the common language established by f-strings (and by the .format method before them).

The necessary code to get these interpolated strings is a bit annoying and can easily be done wrongly (in particular by forgetting about conversion specifiers). Meanwhile, for cases where conversion is important but the usual formatting should be deferred or skipped, it's nice that string.templatelib.convert exists, but it seems like the explicit import shouldn't be necessary.

I propose to smooth this over by adding properties to the Interpolation class, with semantics equivalent to:

# ignoring that the actual implementation is internal
class Interpolation:
    ...
    @property
    def converted(self):
        return string.templatelib.convert(self.value, self.conversion)

    @property
    def formatted(self):
        return format(self.converted, self.format_spec)

With this enhancement, for example, the f-string implementation in the PEP could be simplified to:

def f(template: Template) -> str:
    return ''.join(
        item if isinstance(item, str) else item.formatted
        for item in template
    )

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions