Imagine I have strings containing names of exceptions:
s1 = 'KeyError'
s2 = 'ArithmeticError'
s3 = 'OSError'
s4 = 'ZeroDivisionError'
.....
sn = 'SomeOtherError'
What I need to do is:
if issubclass(s4, (s1, s2, s3, sn)) == True:
print('You dont have to catch this exception because the parent is already caught')
Using globals()
doesn't help in this case for some reason. Since I am not an experienced programmer, I can only guess that it's because those are built-in exceptions...
Nevertheless, what can be done to accomplish what I try to accomplish?
Any suggestions would be appreciated!
The most reliable way is probably to search the class hierarchy. All built-in exceptions are ultimately descendants of BaseException
, so just search its children recursively:
def find_child_class(base, name):
if base.__name__ == name:
return base
for c in base.__subclasses__():
result = find_child_class(c, name)
if result:
return result
>>> find_child_class(BaseException, 'KeyError')
<class 'KeyError'>
This will also work for user-defined exceptions, as long as the module that defines them has been loaded and the exceptions are derived from Exception
(which they should be).