In handling a little SQL formatting I was amazed to find I could chain string formatters:
def get_sql(table, limit=True):
sql = "select report_date from %s"
if limit:
result = "%s limit 1" % sql % table
else:
result = sql % table
return result
Is this legit? Any reason not to do this?
It makes sense that it works because a statement like this:
'some value goes here %s' % valueActually returns a string. It’s probably a bit more logical to view it like this:
result = ("%s limit 1" % sql) % tableThere’s nothing expressly wrong with doing that, but chaining operators can lead to problems with figuring out where an error came from.
So for instance, this works fine:
But if there was a formatting error in there (I realize this example is pathological, but it gets the point across):
It’s really not clear which
%dis causing your error. For that reason, I would split it out and just use one%formatter per line if possible because then the traceback will be able to point you to exactly which line and which formatter had the issue.For the record, by doing it one formatter per line you’ll also make life a lot easier for anyone else who has to read your code and try to figure out what’s going on.