Python Syntax Problem: Comment and Backslash

By Xah Lee. Date:

This is a example of Python syntax idiocy.

why do i get a syntax error in the following?

# traverse the dir, remove temp files
for dpath, dirList, fileList in os.walk(inPath, topdown=False):
    for ff in fileList:
        if (ff == ".htaccess") or \
                (ff == ".DS_Store") or \
                re.search(r"^xx", ff) or \
                re.search(r"^#.+#$", ff) or \
                # re.search(r"~$", ff) or \
                re.search(r"^xx", ff):
            print("◆", ff)
File "/home/xah/git/xahscripts/make_download_copy/delete_temp_files.py3", line 46
    # re.search(r"~$", ff) or \
                              ^
SyntaxError: invalid syntax

if you remove the comment, then it's fine.

here's the tech answer, given by Wang Bin

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

from http://docs.python.org/2/reference/lexical_analysis.html#explicit-line-joining

[—Wang Bin https://plus.google.com/109540056756953832901/posts]

Wang also gave this tip:

BTW, I think a more pythonic way to check is:

for pattern in (r'^\.htaccess$', r'^\.DS_Store$', r'~$', r'^xx'):
    if re.search(pattern, ff):
        print ff

2013-02-21 original discussion https://plus.google.com/112757647855302148298/posts/VdV9mKfB8h2

Python Syntax Suck

  1. Why Python Lambda is Broken and Can't be Fixed
  2. The Fate of Lambda in Python 3000 and Scheme v300
  3. Lambda in Python 3000
  4. Python, Lambda, Guido: is Language Design Just Solving Puzzles?
  5. Python Syntax Soup: x in y
  6. Python Syntax Problem: Comment and Backslash
  7. Syntax Design: Python's Indentation vs Nesting

If you have a question, put $5 at patreon and message me.