SQL syntax highlighting within Python code

SQL syntax highlighting within Python code

Станислав Голев

I've often worked with Python scripts that contained large SQL queries embedded as string literals. To get an idea, see the following code:

sql = '''
SELECT * FROM t
WHERE val > 10
'''
df = run_query(sql)
...

When these SQL queries become lengthy, the lack of syntax highlighting can make them difficult to read. One solution is to move the SQL into separate files and load them at runtime. But what if we had syntax highlighting inside the Python code itself?

VSCode extension

As a VSCode user, I searched for extensions, and the least buggy one I found is "Python SQL" by Azharuddin Syed.

Here is how you use it. At the beginning of a string literal, add --sql:

sql = '''--sql
SELECT * FROM t
WHERE val > 10
'''

And now the content of the string is highlighted as SQL. Since -- starts a line comment in SQL, the addition is eventually ignored.

A note on indentation

If you want to use complex indents in conjunction with textwrap.dedent(), then you have to add extra spaces before --sql to match the indentation level precisely. Or avoid indentation altogether.

Report Page