Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to comment out one line of a multiline statement

Tags:

python

As shown in the following code, the groupby line should be commented out:

lines = fileinput.input(fin) \
        | take(300) \
        | where(lambda x: not x.strip().endswith(',,,,,')) \
        \ # | groupby(lambda x: x[42]) 
        | teeFile(fout,100)

However the above syntax - and several variations on it - does not work:

 \ # | groupby(lambda x: x[42])
                                                                                                                                                                 ^
SyntaxError: unexpected character after line continuation character

Another variation already attempted:

    # | groupby(lambda x: x[42]) \ 

Is there any way to comment out a portion of a longer statement requiring continuation characters? Or are we just out of luck - along the lines of python's inability (/unwillingness) to support inline comments?

I am on 2.7

Update Here is a small update to the code snippet to make it fully self contained.

import sys, pipe, fileinput ; from pipe import *;
lines = fileinput.input(fin) \
        | take(300) \
        | where(lambda x: not x.strip().endswith(',,,,,,,,')) \
        # | groupby(lambda x: x[42]) \
        | tee

It was just including an import now. I get different errors in ipython vs intellij:

ipython :

File "<ipython-input-2-60c5dbee382d>", line 3
    | tee
    ^
IndentationError: unexpected indent

intellij :

 File "<ipython-input-30-1f7b64578a1f>", line 16
    lines = fileinput.input(fin)         | take(300)         | where(lambda x: not x.strip().endswith(',,,,,,,,,,,,,,,,,,,,,'))   \ # | groupby(lambda x: x[42])
                                                                                                                                                                 ^
SyntaxError: unexpected character after line continuation character
like image 261
WestCoastProjects Avatar asked Dec 19 '22 04:12

WestCoastProjects


1 Answers

Use implicit line continuation with parentheses:

lines = (fileinput.input(fin)
        | take(300)
        | where(lambda x: not x.strip().endswith(',,,,,'))
#       | groupby(lambda x: x[42]) 
        | teeFile(fout,100))

Inside unclosed parentheses (, brackets [, or braces {, Python will perform line continuation automatically, even across lines with comments. The rules for line joining with backslashes don't allow line continuation on a line with a comment.

like image 162
user2357112 supports Monica Avatar answered Dec 20 '22 19:12

user2357112 supports Monica