diff -r 0a8509023c09 Doc/library/re.rst --- a/Doc/library/re.rst Sun Jun 05 01:38:29 2016 +0200 +++ b/Doc/library/re.rst Sat Jun 04 18:12:30 2016 -0700 @@ -926,6 +926,17 @@ The pattern string from which the RE object was compiled. +.. attribute:: regex.__code__ + + The compiled bytecode of the regex, as a string. + + .. impl-detail:: + + This attribute is not guaranteed to exist in all implementations of + Python. The bytecode returned is an implementation detail that may change + without warning between CPython versions. + + .. _match-objects: Match Objects diff -r 0a8509023c09 Lib/test/test_re.py --- a/Lib/test/test_re.py Sun Jun 05 01:38:29 2016 +0200 +++ b/Lib/test/test_re.py Sat Jun 04 18:12:30 2016 -0700 @@ -587,6 +587,12 @@ p.groupindex['other'] = 0 self.assertEqual(p.groupindex['other'], 2) + @cpython_only + def test_code(self): + pattern = re.compile('foo') + # contents are implementation-defined + self.assertIsInstance(pattern.__code__, str) + def test_special_escapes(self): self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx").group(1), "bx") diff -r 0a8509023c09 Modules/_sre.c --- a/Modules/_sre.c Sun Jun 05 01:38:29 2016 +0200 +++ b/Modules/_sre.c Sat Jun 04 18:12:30 2016 -0700 @@ -1429,13 +1429,21 @@ PyDoc_STRVAR(pattern_doc, "Compiled regular expression objects"); -/* PatternObject's 'groupindex' method. */ +/* PatternObject's 'groupindex' attribute. */ static PyObject * pattern_groupindex(PatternObject *self) { return PyDictProxy_New(self->groupindex); } +/* PatternObject's '__code__' attribute. */ +static PyObject * +pattern_code(PatternObject *self) +{ + return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, self->code, + self->codesize); +} + static int _validate(PatternObject *self); /* Forward */ /*[clinic input] @@ -2671,6 +2679,8 @@ static PyGetSetDef pattern_getset[] = { {"groupindex", (getter)pattern_groupindex, (setter)NULL, "A dictionary mapping group names to group numbers."}, + {"__code__", (getter)pattern_code, (setter)NULL, + "The pattern's bytecode string."}, {NULL} /* Sentinel */ };