osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python 3.6: How to expand f-string literals read from a file vs inline statement


On Fri, Mar 23, 2018 at 7:37 PM, Malcolm Greene <python at bdurham.com> wrote:
> My original post reformatted for text mode:
>
> Looking for advice on how to expand f-string literal strings whose values I'm reading from a configuration file vs hard coding into
> my script as statements. I'm using f-strings as a very simple template language.
>
> I'm currently using the following technique to expand these f-strings. Is there a better way?

They're not a simple template language; they're a special form of
expression. If you want something you can read from a config file,
look instead at str.format().

# Just an ordinary string at this point, and can be read from a file or anything
product_description_template = "{product_sku} : {product_name}:
${discounted_price}"

# Need to pre-calculate any compound values
discounted_price = product_price * discount
print(product_description_template.format(**locals()))


You can't execute arbitrary code this way, but that's generally a
_good_ thing. If you really want a templating language that can
execute arbitrary code, the best way is to actually make your
templating language BE code; for instance, you can make your config
file be a Python script that creates a bunch of functions, or use
exec/eval directly (though I still wouldn't recommend the latter if
you call this in any sort of tight loop; eval and exec are not cheap,
so it's a lot more efficient to compile once).

ChrisA