On 3/23/18 4:30 AM, Malcolm Greene wrote:
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())
Perhaps it doesn't need to be said, but just to be sure: don't use eval if you don't trust the people writing the configuration file. They can do nearly unlimited damage to your environment. They are writing code that you are running.
--Ned. -- https://mail.python.org/mailman/listinfo/python-list
