Is there a way to write a pandas SQL query across multiple lines with comments?
<p>When writing a regular expression, it is possible to write the expression across multiple lines and including annotation, then compile the expression using the <code>re.VERBOSE</code> option before passing the compiled version. I'd like to do something similar with a <code>pandas.read_sql_query</code>. </p>

<p>For example, instead of:</p>

<pre><code>result = pd.read_sql_query('select a.gvkey, a.tic, a.datadate as fyearend, year(a.datadate) as year, month(a.datadate) as fyrc, b.datadate, month(b.datadate) as month, b.trt1m from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate) where a.TIC = "IBM" and a.datafmt = "STD" and a.consol="C" and a.indfmt = "INDL" and year(a.datadate)&gt;1980', engine)
</code></pre>

<p>I would like to write something like:</p>

<pre><code>q = """select a.gvkey, 
    a.tic,                      #COMMENTS
    a.datadate as fyearend,     #COMMENTS
    year(a.datadate) as year,   #COMMENTS
    month(a.datadate) as fyrc, b.datadate, 
    month(b.datadate) as month, 
    b.trt1m 
    from COMPM.FUNDA a join COMPM.SECM b on a.gvkey = b.gvkey and year(a.datadate) = year(b.datadate) 
    where a.TIC = "IBM" 
        and a.datafmt = "STD" 
        and a.consol="C" 
        and a.indfmt = "INDL" 
        and year(a.datadate)&gt;1980
"""

result = p.read_sql_query(q ,engine)
</code></pre>

<p>My question is related to <a href="https://stackoverflow.com/questions/33944522/is-it-possible-to-split-a-sequence-of-pandas-commands-across-multiple-lines">this</a> question about splitting python commands across multiple lines, but I'd like to add comments inside the query.</p>

<p>As I mentioned, what I'd like to do in the pandas/SQL case is similar to what can be done in the regular expression case with <code>re.VERBOSE</code>. Here is an example with regex:</p>

<pre><code>pattern = r'''\s(shares?| #COMMENTS
            warrants?|       #COMMENTS
            stock|           #AND SO ON...
            (non)?vest(ed)?
            )\b             
            '''
crit = re.compile(pattern_nopt, re.VERBOSE)
match=re.search(crit, string)
</code></pre>

<p>This would make the query more readable and I find it important to annotate queries exhaustively when sharing code with coauthors.</p>