bpo-30397: Add re.Pattern and re.Match. (#1646)

diff --git a/Lib/idlelib/idle_test/test_calltips.py b/Lib/idlelib/idle_test/test_calltips.py
index fa92ece..a58229d 100644
--- a/Lib/idlelib/idle_test/test_calltips.py
+++ b/Lib/idlelib/idle_test/test_calltips.py
@@ -74,7 +74,7 @@
 non-overlapping occurrences of the pattern in string by the
 replacement repl.  repl can be either a string or a callable;
 if a string, backslash escapes in it are processed.  If it is
-a callable, it's passed the match object and must return''')
+a callable, it's passed the Match object and must return''')
         gtest(p.sub, '''(repl, string, count=0)\nReturn the string obtained by replacing the leftmost non-overlapping occurrences o...''')
 
     def test_signature_wrap(self):
diff --git a/Lib/re.py b/Lib/re.py
index c194dba..d772979 100644
--- a/Lib/re.py
+++ b/Lib/re.py
@@ -92,8 +92,8 @@
     subn      Same as sub, but also return the number of substitutions made.
     split     Split a string by the occurrences of a pattern.
     findall   Find all occurrences of a pattern in a string.
-    finditer  Return an iterator yielding a match object for each match.
-    compile   Compile a pattern into a RegexObject.
+    finditer  Return an iterator yielding a Match object for each match.
+    compile   Compile a pattern into a Pattern object.
     purge     Clear the regular expression cache.
     escape    Backslash all non-alphanumerics in a string.
 
@@ -139,7 +139,7 @@
 __all__ = [
     "match", "fullmatch", "search", "sub", "subn", "split",
     "findall", "finditer", "compile", "purge", "template", "escape",
-    "error", "A", "I", "L", "M", "S", "X", "U",
+    "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
     "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
     "UNICODE",
 ]
@@ -175,17 +175,17 @@
 
 def match(pattern, string, flags=0):
     """Try to apply the pattern at the start of the string, returning
-    a match object, or None if no match was found."""
+    a Match object, or None if no match was found."""
     return _compile(pattern, flags).match(string)
 
 def fullmatch(pattern, string, flags=0):
     """Try to apply the pattern to all of the string, returning
-    a match object, or None if no match was found."""
+    a Match object, or None if no match was found."""
     return _compile(pattern, flags).fullmatch(string)
 
 def search(pattern, string, flags=0):
     """Scan through string looking for a match to the pattern, returning
-    a match object, or None if no match was found."""
+    a Match object, or None if no match was found."""
     return _compile(pattern, flags).search(string)
 
 def sub(pattern, repl, string, count=0, flags=0):
@@ -193,7 +193,7 @@
     non-overlapping occurrences of the pattern in string by the
     replacement repl.  repl can be either a string or a callable;
     if a string, backslash escapes in it are processed.  If it is
-    a callable, it's passed the match object and must return
+    a callable, it's passed the Match object and must return
     a replacement string to be used."""
     return _compile(pattern, flags).sub(repl, string, count)
 
@@ -204,7 +204,7 @@
     string by the replacement repl.  number is the number of
     substitutions that were made. repl can be either a string or a
     callable; if a string, backslash escapes in it are processed.
-    If it is a callable, it's passed the match object and must
+    If it is a callable, it's passed the Match object and must
     return a replacement string to be used."""
     return _compile(pattern, flags).subn(repl, string, count)
 
@@ -230,13 +230,13 @@
 
 def finditer(pattern, string, flags=0):
     """Return an iterator over all non-overlapping matches in the
-    string.  For each match, the iterator returns a match object.
+    string.  For each match, the iterator returns a Match object.
 
     Empty matches are included in the result."""
     return _compile(pattern, flags).finditer(string)
 
 def compile(pattern, flags=0):
-    "Compile a regular expression pattern, returning a pattern object."
+    "Compile a regular expression pattern, returning a Pattern object."
     return _compile(pattern, flags)
 
 def purge():
@@ -245,7 +245,7 @@
     _compile_repl.cache_clear()
 
 def template(pattern, flags=0):
-    "Compile a template pattern, returning a pattern object"
+    "Compile a template pattern, returning a Pattern object"
     return _compile(pattern, flags|T)
 
 # SPECIAL_CHARS
@@ -264,13 +264,14 @@
         pattern = str(pattern, 'latin1')
         return pattern.translate(_special_chars_map).encode('latin1')
 
+Pattern = type(sre_compile.compile('', 0))
+Match = type(sre_compile.compile('', 0).match(''))
+
 # --------------------------------------------------------------------
 # internals
 
 _cache = OrderedDict()
 
-_pattern_type = type(sre_compile.compile("", 0))
-
 _MAXCACHE = 512
 def _compile(pattern, flags):
     # internal: compile pattern
@@ -278,7 +279,7 @@
         return _cache[type(pattern), pattern, flags]
     except KeyError:
         pass
-    if isinstance(pattern, _pattern_type):
+    if isinstance(pattern, Pattern):
         if flags:
             raise ValueError(
                 "cannot process flags argument with a compiled pattern")
@@ -301,12 +302,12 @@
     return sre_parse.parse_template(repl, pattern)
 
 def _expand(pattern, match, template):
-    # internal: match.expand implementation hook
+    # internal: Match.expand implementation hook
     template = sre_parse.parse_template(template, pattern)
     return sre_parse.expand_template(template, match)
 
 def _subx(pattern, template):
-    # internal: pattern.sub/subn implementation helper
+    # internal: Pattern.sub/subn implementation helper
     template = _compile_repl(template, pattern)
     if not template[0] and len(template[1]) == 1:
         # literal replacement
@@ -322,7 +323,7 @@
 def _pickle(p):
     return _compile, (p.pattern, p.flags)
 
-copyreg.pickle(_pattern_type, _pickle, _compile)
+copyreg.pickle(Pattern, _pickle, _compile)
 
 # --------------------------------------------------------------------
 # experimental stuff (see python-dev discussions for details)
diff --git a/Lib/sre_constants.py b/Lib/sre_constants.py
index 0261e9e..1daa7bd 100644
--- a/Lib/sre_constants.py
+++ b/Lib/sre_constants.py
@@ -32,6 +32,8 @@
         colno: The column corresponding to pos (may be None)
     """
 
+    __module__ = 're'
+
     def __init__(self, msg, pattern=None, pos=None):
         self.msg = msg
         self.pattern = pattern
diff --git a/Lib/telnetlib.py b/Lib/telnetlib.py
index b0863b1..b9d45b4 100644
--- a/Lib/telnetlib.py
+++ b/Lib/telnetlib.py
@@ -585,12 +585,12 @@
         """Read until one from a list of a regular expressions matches.
 
         The first argument is a list of regular expressions, either
-        compiled (re.RegexObject instances) or uncompiled (strings).
+        compiled (re.Pattern instances) or uncompiled (strings).
         The optional second argument is a timeout, in seconds; default
         is no timeout.
 
         Return a tuple of three items: the index in the list of the
-        first regular expression that matches; the match object
+        first regular expression that matches; the re.Match object
         returned; and the text read up till and including the match.
 
         If EOF is read and no text was read, raise EOFError.
diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py
index 91a0319..437fdd2 100644
--- a/Lib/test/test_optparse.py
+++ b/Lib/test/test_optparse.py
@@ -24,8 +24,6 @@
 from optparse import _match_abbrev
 from optparse import _parse_num
 
-retype = type(re.compile(''))
-
 class InterceptedError(Exception):
     def __init__(self,
                  error_message=None,
@@ -107,7 +105,7 @@
             func(*args, **kwargs)
         except expected_exception as err:
             actual_message = str(err)
-            if isinstance(expected_message, retype):
+            if isinstance(expected_message, re.Pattern):
                 self.assertTrue(expected_message.search(actual_message),
                              """\
 expected exception message pattern:
diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index e9c07a0..9cb426a 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -1596,9 +1596,9 @@
     def test_compile(self):
         # Test return value when given string and pattern as parameter
         pattern = re.compile('random pattern')
-        self.assertIsInstance(pattern, re._pattern_type)
+        self.assertIsInstance(pattern, re.Pattern)
         same_pattern = re.compile(pattern)
-        self.assertIsInstance(same_pattern, re._pattern_type)
+        self.assertIsInstance(same_pattern, re.Pattern)
         self.assertIs(same_pattern, pattern)
         # Test behaviour when not given a string or pattern as parameter
         self.assertRaises(TypeError, re.compile, 0)
diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py
index f19afef..c48a63c 100644
--- a/Lib/unittest/case.py
+++ b/Lib/unittest/case.py
@@ -1273,7 +1273,7 @@
 
         Args:
             expected_exception: Exception class expected to be raised.
-            expected_regex: Regex (re pattern object or string) expected
+            expected_regex: Regex (re.Pattern object or string) expected
                     to be found in error message.
             args: Function to be called and extra positional args.
             kwargs: Extra kwargs.
@@ -1292,7 +1292,7 @@
 
         Args:
             expected_warning: Warning class expected to be triggered.
-            expected_regex: Regex (re pattern object or string) expected
+            expected_regex: Regex (re.Pattern object or string) expected
                     to be found in error message.
             args: Function to be called and extra positional args.
             kwargs: Extra kwargs.