I use f-strings to build SPARQL queries with a variable and they work well as follows:
for label in longnames:
sparqlquery = f"""
PREFIX osr:<http://dati.senato.it/osr/>
SELECT * WHERE {{
?uri a osr:Senatore.
?uri rdfs:label "{label}"^^xsd:string.
}}
"""
which would run N queries with each having a different label value coming from a longnames list[str].
I would like to externalize these SPARQL queries to a separate file and therefore tried to create a sparqlqueries.py file as follows:
DBP_LANGS = """
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX sdo: <https://schema.org/>
CONSTRUCT {
?lang a sdo:Language ;
sdo:alternateName ?iso6391Code .
}
WHERE {
?lang a dbo:Language ;
dbo:iso6391Code ?iso6391Code .
FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values
}
LIMIT {QUERY_LIMIT}
"""
(edit: as noted in the comments that is not an f-string but a simple string literal. Could not use the f-string as the QUERY_LIMIT variable is unknown in that module)
and in my new sample.py code I tried:
from SPARQLWrapper import SPARQLWrapper
from sparqlqueries import DBP_LANGS
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
QUERY_LIMIT = 5
print(DBP_LANGS) # just to debug
sparql.setQuery(DBP_LANGS)
but this SPARQL query fails and as the previous print shows, the QUERY_LIMIT is not interpolated at all in the f-string:
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX sdo: <https://schema.org/>
CONSTRUCT {
?lang a sdo:Language ;
sdo:alternateName ?iso6391Code .
}
WHERE {
?lang a dbo:Language ;
dbo:iso6391Code ?iso6391Code .
FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values
}
LIMIT {QUERY_LIMIT}
and therefore understandably the query fails.
Is there a way to "force" the f-string to be re-interpolated in the current code?