Reputation: 167
I'm trying to dynamically add some additional strings to a query if a file exists that a table is created from. The end ternary works if I remove the first one. I get a syntax error when trying to print out the string below.
testQuery = """
select
fish,
"""+("""Room,""" if os.path.isfile(schoolFile)==True else """""")+
"""period_01,
period_02
from over_cs_doe d
"""+("""LEFT JOIN schools s ON s.fish=d.fish""" if os.path.isfile(schoolFile)==True else """""")
Upvotes: 0
Views: 3100
Reputation: 5415
For Python 3.6 onward I would use f-strings, no need to worry about line continuation or positional interpolation like the %s
placehholders.
For example:
is_school_file = os.path.isfile(schoolFile)
testQuery = f"""
select
fish,
{" room," if is_school_file else ""}
period_01,
period_02
from over_cs_doe as d
{"left join schools as s ON s.fish=d.fish" if is_school_file else ""}"""
If you are using a DB-API compliant database library, or and ORM like SQLAlchemy then there are safer ways to contruct queries that avoid SQL injection. This doesn't look like a case where there might be any unsanitized user-input, but it is responsible to mention it wherever people are concatenating strings to create SQL statements, because SQL Injection is still the #1 code vulnerability.
Upvotes: 0
Reputation: 2120
Your code is almost ok, the problem is that you must use \
at the end of the line if you intend to continue you statement in the next line
testQuery = """
select
fish,
"""+("""Room,""" if os.path.isfile(schoolFile) else """""") + \ #Use backslash to continue your statement
"""period_01,
period_02
from over_cs_doe d
"""+("""LEFT JOIN schools s ON s.fish=d.fish""" if os.path.isfile(schoolFile) else """""")
Also as I said in a comment, don't test if a boolean values is true
Upvotes: 3
Reputation: 1603
You can mix strings and code this way but it's not easy to read. Why not trying something like :
if os.path.isfile(schoolFile):
testQuery = """
select Fish,Room,period_01 ...
from ...
"""
else:
testQuery = """
select Fish,period_01 ...
from ...
"""
Upvotes: 0
Reputation: 9696
For what it's worth, a much more readable and less error prone alternative would be using string interpolation rather than concatenation.
Plus, as the comments suggest, 'something == True' in a "boolean" manner is certainly not considered good style. The same applies to using triple-quoted strings where they aren't needed.
So, your testQuery could also look like:
testQuery = """
select
fish,
%s
period_01,
period_02
from over_cs_doe d
%s
""" % ("Room," if os.path.isfile(schoolFile) else "",
"LEFT JOIN schools s ON s.fish=d.fish" if os.path.isfile(schoolFile) else "")
Upvotes: 0