【发布时间】:2014-01-04 21:21:28
【问题描述】:
在 python 中,如何在不实际运行函数的情况下检查函数是否存在(即使用 try)?我会测试它是否存在于模块中。
【问题讨论】:
-
取决于上下文,如果是一个类,如果是全局定义,你必须扩展问题以提供更多元素。
标签: python function python-2.7 try-catch
在 python 中,如何在不实际运行函数的情况下检查函数是否存在(即使用 try)?我会测试它是否存在于模块中。
【问题讨论】:
标签: python function python-2.7 try-catch
你建议tryexcept。您确实可以使用它:
try:
variable
except NameError:
print("Not in scope!")
else:
print("In scope!")
这会检查variable 是否在范围内(它不调用函数)。
【讨论】:
variable()。它只是检查是否定义了variable。
Solution1:
import inspect
if (hasattr(m, 'f') and inspect.isfunction(m.f))
Solution2:
import inspect
if ('f' in dir(m) and inspect.isfunction(m.f))
地点:
m = 模块名称
f = m 中定义的函数
【讨论】:
如果您正在检查包中是否存在函数:
import pkg
print("method" in dir(pkg))
如果您正在检查脚本/命名空间中是否存在函数:
def hello():
print("hello")
print("hello" in dir())
【讨论】:
如果您要在代码中查找函数,请使用 global()
if "function" in globals():
...
【讨论】:
如果你在类中寻找函数,你可以使用“__dict__”选项。例如,检查“some_class”中的函数“some_function”是否执行:
if "some_function" in list(some_class.__dict__.keys()):
print('Function {} found'.format ("some_function"))
【讨论】:
hasattr(some_class, "some_function") 更清楚,因为有时不使用 dict,尽管这仍然不能检查您是否正在处理函数。