在python脚本中使用'type'动态定义临时异常类,用作模块。如果在导入脚本中捕获到此类的实例,则它无法识别该类。 以下是代码段
# the throwing module, defines dynamically
def bad_function():
ExceptionClass = type( "FooBar", (Exception,),
{ "__init__": lambda self, msg: Exception.__init__(self, msg) })
raise ExceptionClass("ExceptionClass")
使用代码
import libt0
try:
libt0.bad_function()
#except libt0.FooBar as e:
#print e
except Exception as e:
print e
print e.__class__
可以解释为什么libt0.FooBase对这个脚本不可见吗?最后一行的观察者输出。
答案 0 :(得分:2)
您在函数内创建了类,因此它不作为模块的全局命名空间中的名称存在。事实上,除了bad_function
正在执行时,它根本不存在。这也是失败的原因:
# file1.py
def good_function():
x = 2
# file2.py
import file1
print file1.x
您的异常类只是bad_function
内的一个局部变量。
答案 1 :(得分:2)
目前尚不清楚如何在不做类似事情的情况下让FooBar存在
def bad_function():
ExceptionClass = type( "FooBar", (Exception,),
{ "__init__": lambda self, msg: Exception.__init__(self, msg) })
globals()['FooBar'] = ExceptionClass
raise ExceptionClass("ExceptionClass")