Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 12723ba

Browse files
committed
Fix and test for bug #764548:
Use isinstance() instead of comparing types directly, to enable subclasses of str and unicode to be used as patterns. Blessed by /F.
1 parent 5e4e39f commit 12723ba

3 files changed

Lines changed: 17 additions & 7 deletions

File tree

Lib/sre.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,9 @@ def _compile(*key):
219219
if p is not None:
220220
return p
221221
pattern, flags = key
222-
if type(pattern) is _pattern_type:
222+
if isinstance(pattern, _pattern_type):
223223
return pattern
224-
if type(pattern) not in sre_compile.STRING_TYPES:
224+
if not isinstance(pattern, sre_compile.STRING_TYPES):
225225
raise TypeError, "first argument must be string or compiled pattern"
226226
try:
227227
p = sre_compile.compile(pattern, flags)

Lib/sre_compile.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -428,12 +428,12 @@ def _compile_info(code, pattern, flags):
428428
_compile_charset(charset, flags, code)
429429
code[skip] = len(code) - skip
430430

431-
STRING_TYPES = [type("")]
432-
433431
try:
434-
STRING_TYPES.append(type(unicode("")))
432+
unicode
435433
except NameError:
436-
pass
434+
STRING_TYPES = type("")
435+
else:
436+
STRING_TYPES = (type(""), type(unicode("")))
437437

438438
def _code(p, flags):
439439

@@ -453,7 +453,7 @@ def _code(p, flags):
453453
def compile(p, flags=0):
454454
# internal: convert pattern list to internal format
455455

456-
if type(p) in STRING_TYPES:
456+
if isinstance(p, STRING_TYPES):
457457
import sre_parse
458458
pattern = p
459459
p = sre_parse.parse(p, flags)

Lib/test/test_re.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,16 @@ def test_bug_725149(self):
474474
self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
475475
('a', None, None))
476476

477+
def test_bug_764548(self):
478+
# bug 764548, re.compile() barfs on str/unicode subclasses
479+
try:
480+
unicode
481+
except NameError:
482+
return # no problem if we have no unicode
483+
class my_unicode(unicode): pass
484+
pat = re.compile(my_unicode("abc"))
485+
self.assertEqual(pat.match("xyz"), None)
486+
477487
def test_finditer(self):
478488
iter = re.finditer(r":+", "a:b::c:::d")
479489
self.assertEqual([item.group(0) for item in iter],

0 commit comments

Comments
 (0)