Python 检查函数是否存在而不运行它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20926909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:34:01  来源:igfitidea点击:

Python check if function exists without running it

pythonfunctionpython-2.7try-catch

提问by Josh Wood

In python how do you check if a function exists without actually running the function (i.e. using try)? I would be testing if it exists in a module.

在python中,如何在不实际运行函数(即使用try)的情况下检查函数是否存在?我会测试它是否存在于模块中。

采纳答案by Josh Wood

You can use dirto check if a name is in a module:

您可以使用dir来检查名称是否在模块中:

>>> import os
>>> "walk" in dir(os)
True
>>>

In the sample code above, we test for the os.walkfunction.

在上面的示例代码中,我们测试了该os.walk函数。

回答by rlms

You suggested tryexcept. You could indeed use that:

你建议tryexcept. 你确实可以使用它:

try:
    variable
except NameError:
    print("Not in scope!")
else:
    print("In scope!")

This checks if variableis in scope (it doesn't call the function).

这将检查是否variable在范围内(它不调用该函数)。

回答by Paula Cogeanu

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

where:
m = module name
f = function defined in m

其中:
m = 模块名称
f = 在 m 中定义的函数

回答by openwonk

If you are checking if function exists in a package:

如果要检查包中是否存在函数:

import pkg

print("method" in dir(pkg))

If you are checking if function exists in your script / namespace:

如果您正在检查脚本/命名空间中是否存在函数:

def hello():
    print("hello")

print("hello" in dir())

回答by kenisam

If you are looking for the function in class, you can use a "__dict__" option. E.g to check if the function "some_function" in "some_class" do:

如果您正在类中查找函数,则可以使用“__dict__”选项。例如,检查“some_class”中的函数“some_function”是否执行:

if "some_function" in list(some_class.__dict__.keys()):
    print('Function {} found'.format ("some_function"))