◐ Shell
clean mode source ↗

Issue 22578: Add additional attributes to re.error

Proposed patch adds additional attributes to the re.error exception: msg, pattern, pos, colno, lineno. It also adds helpful information to error message.

Examples:

>>> re.compile(r"abc\u123")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/serhiy/py/cpython/Lib/re.py", line 220, in compile
    return _compile(pattern, flags)
  File "/home/serhiy/py/cpython/Lib/re.py", line 287, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/home/serhiy/py/cpython/Lib/sre_compile.py", line 465, in compile
    p = sre_parse.parse(p, flags)
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 797, in parse
    p = _parse_sub(source, pattern, 0)
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 387, in _parse_sub
    itemsappend(_parse(source, state))
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 767, in _parse
    code = _escape(source, this, state)
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 378, in _escape
    raise source.error("bogus escape: %s" % repr(escape), len(escape))
sre_constants.error: bogus escape: '\\u123' at position 3
>>> re.compile("""
...     (?x)
...     .++
... """)
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/home/serhiy/py/cpython/Lib/re.py", line 220, in compile
    return _compile(pattern, flags)
  File "/home/serhiy/py/cpython/Lib/re.py", line 287, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/home/serhiy/py/cpython/Lib/sre_compile.py", line 465, in compile
    p = sre_parse.parse(p, flags)
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 797, in parse
    p = _parse_sub(source, pattern, 0)
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 387, in _parse_sub
    itemsappend(_parse(source, state))
  File "/home/serhiy/py/cpython/Lib/sre_parse.py", line 602, in _parse
    source.tell() - here + len(this))
sre_constants.error: multiple repeat at position 16 (line 3, column 7)

See also PEP 473, issue19361 and issue22364.