Command Line Run Module SyntaxWarning: invalid escape sequence '\

Hi,

I am currently running a few modules from the command line. I came across this oddest of issues. When I run the following script via the following command line: python welcome.py:

"""
   welcome.py

   Desktop\socket_scripts\welcome.py

"""

print('Welcome to the Python forum!')

I get the following warning:

SyntaxWarning: invalid escape sequence '\s'

Apparently it reads the comments at the top of the module. But if they’re comments, why would it care if there are backspaces? Shouldn’t it ignore the comment section?

That’s not a comment. That’s a string literal.

You’re using it as a comment or docstring, but it’s still a string.

Yeah, I tend to to use the same naming convention for both. :wink:

In any case, if it is not code, why would it matter? Because it is a “string” (docstring at that)?

A string is a string and is code, and the rules don’t change just because it’s being used as a comment or docstring.

1 Like

Ok, fair enough. Using double backspace cleans it up.

Thank you.

Do you still get the error if it starts with r"""? Or how about f""" together with the hardcoded path replaced with {__file__} ?

1 Like

If I prefix the docstring with “r”, I don’t get the warning. If I prefix it with “f”, I still do.

Workarounds:

  1. Use double backspaces (\\)
    or
  2. Prefix docstring with “r

Try prefixing it with f -and- replacing Desktop\socket_scripts\welcome.py with {__file__}

Do you mean like this?:

f"""
   welcome.py

   {__Desktop\socket_scripts\welcome.py__}

"""

Then I get this error:

File "C:\Desktop\socket_scripts\welcome.py", line 5
    {__Desktop\socket_scripts\welcome.py__}
                                   ^
SyntaxError: unexpected character after line continuation character

If I just use the filename, I also get an error.

In an f-string, whatever is between braces is an expression to be evaluated.

__Desktop\socket_scripts\welcome.py__ is not a valid expression.

Do you mean like this?:

No, __file__ is a magic variable Python puts in the namespace, like __name__.

Yes, that works. But then that defeats the whole purpose since I want to include the pathname along with the module name. These are module comments after all with information stating where the module is located.

Sure. It’s just a suggestion. You’re the one maintaining it. I just wondered if using Python based doc tools that import the code base, whether this might be more robust and result in less work.

Or how about f""" together with the hardcoded path replaced with {__file__} ?

f-strings cannot be used as doc strings.

Ah, right you are. I didn’t realise that. Thankyou.