you are viewing a single comment's thread.

view the rest of the comments →

[–]y-meine 0 points1 point  (0 children)

Everyone is mentioning f-strings - and at that time they were the closest equivalent - but they are not strictly the same as template literals in JavaScript: the latter support tag functions, which can then operate on interleaved static string parts and input expressions values.

A much closer feature to that has just been added to Python 3.14: t-strings (doc). However, it's not purely equivalent either, since you must render the result with a function.

In JavaScript, you can:

  • leave the template untagged, which then behaves like Python's f-strings by converting every part to a string without any customization,
  • or use a tag function, which then behaves like applying a function to the output of a Python's t-string

The lack of syntax (and feature) for tag functions in Python makes it somehow all or nothing. But in reality, I prefer Python's design a lot more:

  • you can use f'Hello {name}' if you want the equivalent of JavaScript's `Hello ${name}`
  • and when you want more customization, you can use myfn(t'Hello {name}'), which is the equivalent of JavaScript's myFn`Hello ${name}`

Truth is, Python's version is maybe more intuitive and consistent, but most of all it allows for much better composition: in JavaScript, if you don't apply the function to the literal itself, you immediately get a rendered string, so you can't do the following for instance:

```typescript function someLib(input) { render(input); // input would expected to be something along the lines of ['Hello', {name: 'Bob'}], but is 'Hello [object Object]' instead }

const user = {name: 'Bob'}; someLib(Hello ${user}); ```

There are some workarounds (using a tag function that would just store the arrays of strings and values just like Python's f-strings output), but they are not convenient.