Search code examples
python-3.x

How to Evaluate nested f-strings in Python?


I have an f-string that has placeholders which is not getting evaluated. Sample code below shows the closest I am trying to achieve.

SourceSchema = 'myschema'
SourceTable = 'mytable'
SourceQuery = 'SELECT * FROM {SourceSchema}.{SourceTable}'
print(f"{SourceQuery}")

Result: It's evaluated as literal

SELECT * FROM {SourceSchema}.{SourceTable}

What I need is

SELECT * FROM myschema.mytable

Is there a simple way of achieving it?


Solution

  • f-strings are always evaluated in the place they are located in the code - that evaluation cannot be postponed.

    So, this should work like you intend to:

    SourceSchema = 'myschema'
    SourceTable = 'mytable'
    SourceQuery = f'SELECT * FROM {SourceSchema}.{SourceTable}'
    print(f"{SourceQuery}")
    
    

    Of course, this won´t help if you want your query-templates to be fetched from another function or file.

    In that case, instead of query-strings, you have to resort to call a string's .format method, passing it the variables you want to use inside the string as parameters:

    SourceSchema = 'myschema'
    SourceTable = 'mytable'
    # query template which can be retrieved dynamically:
    SourceQuery = 'SELECT * FROM {SourceSchema}.{SourceTable}'
    # rendering with the local variables:
    final_query = SourceQuery.format(SourceSchema=SourceSchema, SourceTable=SourceTable)