markupsafe icon indicating copy to clipboard operation
markupsafe copied to clipboard

t-strings support

Open xmo-odoo opened this issue 3 months ago • 2 comments

With the release of Python 3.14, t-strings (PEP 750) seem well suited to markupsafe e.g.

Markup(t'foo {bar} baz')

should be similar to

Markup("foo %s baz") % bar

possibly easier to lint and typecheck.

While it would work nicely by just adding __html__ to string.templatelib.Template, that is not an option:

>>> Template.__html__ = None
...
TypeError: cannot set '__html__' attribute of immutable type 'string.templatelib.Template'

so sadly in order for this to work markupsafe needs dedicated support.

Open question: should escape(t'foo {bar} baz') behave the same as Markup(t'foo {bar} baz')? That would parallel the __html__ protocol, which I think is reasonable.

I'd be glad to contribute this, I already have the start of an implementation.

xmo-odoo avatar Oct 08 '25 08:10 xmo-odoo

hmmm... I never thought about using t-strings with markupsafe but I like the idea.

the only risk I see there that if someone accidentally uses an f-string instead, it'd suddenly be very unsafe. but I guess that's something inters could take care of

ThiefMaster avatar Oct 08 '25 08:10 ThiefMaster

the only risk I see there that if someone accidentally uses an f-string instead, it'd suddenly be very unsafe. but I guess that's something inters could take care of

Yeah that's what I figure, technically it's already an issue as you can pass an f-string instead of a literal string, we guard against that via a linter (requiring that only string literals be passed to markupsafe).

Eventually it might be possible to only support t-strings as inputs and ban str completely, but that's probably in a very far future.

xmo-odoo avatar Oct 08 '25 09:10 xmo-odoo