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

Malcolm Greene python at bdurham.com
Fri Mar 23 04:30:49 EDT 2018


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?
Bonus if anyone has suggestions on how my expand() function can access
the locals() value of the caller so this parameter doesn't have to be
passed in explicitly.
*def *expand(expression, values):
 """Expand expression using passed in locals()"""
 triple_quote = *"'" ** 3
 expression = dedent(expression)
 *return *eval(*f'f{triple_quote}{expression}{triple_quote}'*,
 *None*, values)
product_name = 'Bike ABC'
product_sku = '123456'
product_price = 299.95
discount = 0.85
# read in product description template 
# product_description_template might look like: {product_sku} :
# {product_name}: ${product_price * discount}product_description_template = config('product_description_template')
# expand the {expressions} in product_description_template using my
# locals()product_description = expand(product_description_template, locals())


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /