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

Skip to content

Commit afb2c80

Browse files
committed
ceval.c/do_raise(): Tighten the test to disallow raising an instance of
a str subclass. test_descr.py/string_exceptions(): New sub-test. For 2.3 only. Guido doesn't want this backported.
1 parent 16af557 commit afb2c80

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

Lib/test/test_descr.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2974,6 +2974,31 @@ class NewClass(object):
29742974
vereq(NewClass.__doc__, 'object=None; type=NewClass')
29752975
vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
29762976

2977+
def string_exceptions():
2978+
if verbose:
2979+
print "Testing string exceptions ..."
2980+
2981+
# Ensure builtin strings work OK as exceptions.
2982+
astring = "An exception string."
2983+
try:
2984+
raise astring
2985+
except astring:
2986+
pass
2987+
else:
2988+
raise TestFailed, "builtin string not usable as exception"
2989+
2990+
# Ensure string subclass instances do not.
2991+
class MyStr(str):
2992+
pass
2993+
2994+
newstring = MyStr("oops -- shouldn't work")
2995+
try:
2996+
raise newstring
2997+
except TypeError:
2998+
pass
2999+
except:
3000+
raise TestFailed, "string subclass allowed as exception"
3001+
29773002
def test_main():
29783003
class_docstrings()
29793004
lists()
@@ -3039,6 +3064,7 @@ def test_main():
30393064
funnynew()
30403065
imulbug()
30413066
docdescriptor()
3067+
string_exceptions()
30423068
if verbose: print "All OK"
30433069

30443070
if __name__ == "__main__":

Python/ceval.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2743,7 +2743,10 @@ do_raise(PyObject *type, PyObject *value, PyObject *tb)
27432743
Py_DECREF(tmp);
27442744
}
27452745

2746-
if (PyString_Check(type))
2746+
if (PyString_CheckExact(type))
2747+
/* Raising builtin string is deprecated but still allowed --
2748+
* do nothing. Raising an instance of a new-style str
2749+
* subclass is right out. */
27472750
;
27482751

27492752
else if (PyClass_Check(type))

0 commit comments

Comments
 (0)