3 ms·
There's a subtle bug with: def exception_instance(obj): if isinstance(obj, BaseException): return obj elif isinstance(obj, type) and is
by eesmith 5y ago
There's a subtle bug with:
def exception_instance(obj):
if isinstance(obj, BaseException):
return obj
elif isinstance(obj, type) and issubclass(obj, BaseException):
return obj()
else:
raise TypeError("exceptions must derive from BaseException")
Calling a class doesn't mean the result is a subclass. That's defined by __new__.
>>> class Spam(Exception):
... def __new__(self):
... return 4
...
>>> Spam()
4
I can't pass a Spam class as the __cause__:
>>> exc1 = Exception()
>>> exc1.__cause__ = Spam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
but:
>>> exception_instance(Spam)
4
the following would handle that case:
def exception_instance(obj):
if isinstance(obj, type) and issubclass(obj, BaseException):
obj = obj()
if isinstance(obj, BaseException):
return obj
else:
raise TypeError("exceptions must derive from BaseException")