Is there a callable equivalent to f-string syntax?

2024/11/15 10:05:57

Everybody loves Python 3.6's new f-strings:

In [33]: foo = {'blah': 'bang'}In [34]: bar = 'blah'In [35]: f'{foo[bar]}'
Out[35]: 'bang'

However, while functionally very similar, they don't have the exact same semantics as str.format():

In [36]: '{foo[bar]}'.format(**locals())
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-36-b7ef5aead76c> in <module>()
----> 1 '{foo[bar]}'.format(**locals())KeyError: 'bar'

In particular, str.format() handles getitem syntax very differently:

In [39]: '{foo[blah]}'.format(**locals())
Out[39]: 'bang'

Given the ability to handle full-blown python expression syntax, f-strings are wonderful and I love them. But they have one hitch: they're evaluated immediately, whereas with str.format() I can save the string with its formatting as a template, and format it multiple times in different contexts.

So, is there an equivalent way to save a string as a template, and evaluate it, using f-string semantics, at a later date? Other than defining a function? Is there an equivalent to str.format() for f-strings?

Update:

So, hypothetical interface here as an example:

In [40]: mystr = '{foo[bar]}'In [41]: make_mine_fstring(mystr, foo=foo, bar=bar)
Out[41]: 'bang'
Answer

Brief answer: NO.

You can read PEP-498 regarding these f-strings. It clearly defines their purpose, and the concept: these strings are evaluated in-place. The result is a usual str with formatted content. You cannot store f-strings as a template, as there is no special object for f-strings.

Your specific example is also mentioned in PEP-498's "Differences between f-string and str.format expressions" section.

So, whatever you do, you either use the inline in-place f-strings, or the old s.format() syntax, with different behaviour.

If you want to read an f-string from a file and evaluate it according to the syntax of f-strings, you could use eval:

foo = {'blah': 'bang', 'bar': 'sorry'}
bar = 'blah'tpl = '{foo[bar]}'
print(tpl)print(tpl.format(**locals()))  # sorry
print(eval(f'f{tpl!r}'))  # bang

Note how we use the f-string first, but convert the tpl into its own repr for immediate eval. Typically, for simple types, eval(repr(val)) should return val. But instead of just putting repr(tpl) (or {tpl!r}), we convert the repr of the regular string into the f-string, and evaluate it instead.

https://en.xdnf.cn/q/72130.html

Related Q&A

Python: list comprehension based on previous value? [duplicate]

This question already has answers here:Python list comprehension - access last created element(9 answers)Closed 10 months ago.Say I want to create a list using list comprehension like:l = [100., 50., 2…

How to run a coroutine inside a context?

In the Python docs about Context Vars a Context::run method is described to enable executing a callable inside a context so changes that the callable perform to the context are contained inside the cop…

Random Forest interpretation in scikit-learn

I am using scikit-learns Random Forest Regressor to fit a random forest regressor on a dataset. Is it possible to interpret the output in a format where I can then implement the model fit without using…

Why are three apostrophes needed for print in Python?

Im making this Pythagoras Theorem Calculator in Python 3.3.2.I made print over several lines so that I could make a diagram:print("Welcome to the Pythagoras Theorem Calculator, powered by Python!&…

Downloading files from public Google Drive in python: scoping issues?

Using my answer to my question on how to download files from a public Google drive I managed in the past to download images using their IDs from a python script and Google API v3 from a public drive us…

Change locale for django-admin-tools

In my settings.py file I have:LANGUAGE_CODE = ru-RUalso, I have installed and working django-admin-tools. But admin language still english. What Im doing wrong?PS.$ cat settings.py | grep USE | grep -…

Container localhost does not exist error when using Keras + Flask Blueprints

I am trying to serve a machine learning model via an API using Flasks Blueprints, here is my flask __init__.py filefrom flask import Flaskdef create_app(test_config=None):app = Flask(__name__)@app.rout…

Serving static files with WSGI and Python 3

What is the simplest way to serve static files with WSGI and Python 3.2? There are some WSGI apps for PEP 333 and Python 2 for this purpose - but was is about PEP 3333 and Python 3? I want to use wsg…

Force INNER JOIN for Django Query

Here is my schema:City PhotographerIm trying to get a list of cities that have at least one photographer, and return the photographer count for the cities.Here is the queryset Im working with:City.obj…

Sklearn Decision Rules for Specific Class in Decision tree

I am creating a decision tree.My data is of the following typeX1 |X2 |X3|.....X50|Y _____________________________________ 1 |5 |7 |.....0 |1 1.5|34 |81|.....0 |1 4 |21 |21|.... 1 |0 65 |34 |23|..…