【问题标题】:Python: How to get exception as an object from a string with the same name?Python:如何从同名字符串中获取异常作为对象?
【发布时间】:2021-08-26 19:02:16
【问题描述】:

假设我有包含异常名称的字符串:

s1 = 'KeyError'
s2 = 'ArithmeticError'
s3 = 'OSError'
s4 = 'ZeroDivisionError'
.....
sn = 'SomeOtherError'

我需要做的是:

if issubclass(s4, (s1, s2, s3, sn)) == True:
print('You dont have to catch this exception because the parent is already caught')

由于某种原因,在这种情况下使用 globals() 没有帮助。由于我不是经验丰富的程序员,我只能猜测是因为那些是内置异常...

然而,我可以做些什么来完成我想要完成的事情?

任何建议将不胜感激!

【问题讨论】:

  • 你有什么理由首先将异常作为字符串?
  • @MisterMiyagi 它们来自用户输入的字符串

标签: python string exception inheritance subclass


【解决方案1】:

最可靠的方法可能是搜索类层次结构。所有内置异常最终都是BaseException 的后代,因此只需递归搜索其子项:

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'>

这也适用于用户定义的异常,只要定义它们的模块已加载并且异常源自Exception(它们应该是)。

【讨论】:

    【解决方案2】:

    globals() 会起作用,如果你以正确的方式使用它:

    getattr(globals()['__builtins__'], 'KeyError')
    <class 'KeyError'>
    

    【讨论】:

    • 这可能看起来有效,但它在除__main__ 之外的任何模块中都失败了。此外,__builtins__ 是一个实现细节。 import the builtins module 会更有意义。
    • (即使这个答案中的代码可靠的,当你可以写@时,通过globals()到达__builtins__没有任何意义987654329@.)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2014-08-21
    • 2013-07-31
    相关资源
    最近更新 更多