Evaluation of variable as f-string

Johannes Bauer dfnsonfsduifb at gmx.de
Sun Jan 29 04:18:00 EST 2023


Am 29.01.23 um 05:27 schrieb Thomas Passin:

> Well, yes, we do see that.  What we don't see is what you want to 
> accomplish by doing it, and why you don't seem willing to accept some 
> restrictions on the string fragments so that they will evaluate correctly.

I'll have to accept the restrictions. That's a good enough answer for 
me, actually. I was just thinking that possibly there's something like 
(made-up code):

x = { "foo": "bar" }
fstr = string.fstring_compile(s)
fstr.eval(x = x)

Which I didn't know about. It would make sense to me, but possibly not 
enough of a usecase to make it into Python. The format() flavors do not

> IOW, perhaps there is a more practical way to accomplish what you want. 
> Except that we don't know what that is.

Well, I don't know. I pretty much want a generic Python mechanism that 
allows for exactly what f-strings do: execute arbitrary Python snippets 
of code and format them in one go. In other words, I want to be able to 
do things like that, given an *arbitrary* dictionary x and a string s 
(which has the only restriction that its content needs to be vald 
f-string grammar):

x = {
	"d": 12,
	"t": 12345,
	"dt": datetime.datetime,
	"td": datetime.timedelta
}
s = "{x['d']:09b} {'->' * (x['d'] // 3)} {(x['dt'](2000, 1, x['d']) + 
x['td'](120)).strftime('%y.%m.%d')} {'<-' * (x['d'] // 4)}"
q = magic_function(s, x = x)

and have "q" then be

'000001100 ->->->-> 00.05.11 <-<-<-'

I believe the closest solution would be using a templating mechanism 
(like Mako), but that has slightly different syntax and doesn't do 
string formatting as nice as f-strings do. f-strings really are the 
perfect syntax for what I want to do.

Cheers,
Johannes


More information about the Python-list mailing list