Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chained string formatting in Python

Tags:

python

string

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?

like image 241
EMiller Avatar asked Jan 21 '23 18:01

EMiller


1 Answers

It makes sense that it works because a statement like this:

'some value goes here %s' % value

Actually returns a string. It's probably a bit more logical to view it like this:

result = ("%s limit 1" % sql) % table

There'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:

>>> sql = 'a value of %s'
>>> x = 'some string %s with stuff'
>>> y = 'VALUE'
>>> x % sql % y
'some string a value of VALUE with stuff'

But if there was a formatting error in there (I realize this example is pathological, but it gets the point across):

>>> sql = 'a value of %d'
>>> x = 'some string %d with stuff'
>>> y = 123    
>>> x % sql % y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

It's really not clear which %d is 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.

like image 197
Brent Writes Code Avatar answered Jan 24 '23 07:01

Brent Writes Code