Why Isn't There a Template Object for String Formatting in Python?
Asked by
dishwasher.rack
I'm curious about the absence of a way to directly convert a string into a template object in Python, similar to how we can use `str.format()` and f-strings. I get that we can create a template string literal, such as `t"The {what} is {value}."`, but I can't seem to find a method to use a dictionary to create a template object. For example, I'd like to do something like `"The {what} is {value}".template(values)` where `values` represents `{'what': 'answer', 'value': 42}`. This feels like a missing feature and complicates things when I want to implement some ideas I have. Is there a workaround I'm overlooking, or is Python just not set up for this kind of operation?
Answers
If you want a more generic solution, you could consider a little workaround. For example, you could define a function that evaluates `t` with your template string in a way that respects your variables. Still, this approach involves using `eval`, and I get that this might not feel clean and is generally not a preferred practice.
Reply to this answer
The main idea behind template strings is that their placeholders are linked directly to the values of expressions, so they're more akin to lambda functions than traditional strings. You can definitely create non-literal template objects, but this requires parsing them manually using the Template constructor from the standard library. It seems like a built-in way to directly convert a string into a template might not be necessary because most code can wrap the string in a simple function instead. For instance, you could write a function that does this without needing extra complexity.
Reply to this answer
It's even more frustrating because calling `str(my_template)` doesnโt yield the expected string output. You have a string object but using `str()` on it doesnโt return the string itself, which makes it feel poorly designed. Templates aren't really meant for that, so if that's what you're after, a template might not be the right fit for your needs.
Reply to this answer
Don't forget about f-strings! They offer a very Pythonic way to embed expressions inside string literals, but I understand you're looking for something specific related to template objects.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions