Skip to content

Make SyntaxWarning for invalid escape sequences better reflect their intended deprecation #128016

Closed
@umarbutler

Description

@umarbutler

Feature or enhancement

Proposal:

I would like to propose that the SyntaxWarning that is raised when an invalid escape sequence is used be updated to better reflect the fact that the ability of Python users to employ invalid escape sequences is intended to be removed in a future Python release.

At present, if one runs the code path = 'C:\Windows' in Python, they get this warning: SyntaxWarning: invalid escape sequence '\W'.

I argue that that warning is not as semantically meaningful as it could be. It does not immediately convey to the untrained and/or uninitiated that path = 'C:\Windows' will in fact break in a future Python release.

What is a better of way communicating that? How about, SyntaxWarning: '\W' is currently an invalid escape sequence. In the future, invalid escape sequences will raise a SyntaxError. Did you mean '\\W'?.

That message is a little bit longer but it immediately tells the user, without the need for heading to Stack Overflow or Python documentation, that:

  1. Although the code runs today, it won't run soon!
  2. You can fix the code easily, just add an extra backslash.

Whereas all that SyntaxWarning: invalid escape sequence '\W' tells me is, at best, hey, there's something wrong here, but you've gotta figure out what that is. Someone could easily read that message and think maybe Python is trying to be helpful and make me double check that I didn't actually mean to type a valid escape sequence like \f or \n.

A message like SyntaxWarning: '\W' is currently an invalid escape sequence. In the future, invalid escape sequences will raise a SyntaxError. Did you mean '\\W'? makes it much more difficult to come away with the message that the Python developers might not like what I've just done but it works and it'll keep working forever.


Update: The proposed message has been revised to "\W" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\W"? following consultation.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/make-syntaxwarning-for-invalid-escape-sequences-better-reflect-their-intended-deprecation/74416/2

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions