Python, 检查模块是否具有特定功能

Python, checking if a module has a certain function

我需要知道 python 模块 函数 是否存在,无需导入它。

导入可能不存在的东西(不是我想要的): 这是我目前所拥有的,但它只适用于整个模块而不适用于模块功能。

import imp
try:
    imp.find_module('mymodule')
    found = True
except ImportError:
    found = False

上面的代码用于查找模块是否存在,下面的代码是我想要的功能,但是这段代码不起作用。

import imp
try:
    imp.find_module('mymodule.myfunction')
    found = True
except ImportError:
    found = False

它给出了这个错误:

No module named mymodule.myfunction

我知道 mymodule.myfunction 确实作为函数存在,因为如果我使用以下方式导入它,我就可以使用它:

import mymodule.myfunction

但是,我知道它不是一个模块,所以这个错误确实有道理,我只是不知道如何解决它。

怎么样:

try:
    from mymodule import myfunction
except ImportError:
    def myfunction():
        print("broken")

I know that mymodule.myfunction does exist as a function because I can use it if I import it using:

import mymodule.myfunction

否 -- 如果可行,则 myfunction 是 mymodule 包的子模块。

您可以导入模块并检查其 vars(),或对其执行 dir(),甚至使用像 astor 这样的包来检查它而不导入它。但是这里的问题似乎要基本得多——如果你可以键入 import mymodule.myfunction 而没有出现错误,那么 myfunction 就是在骗你——它不是真正的函数。

你想要的不可能。

如果不执行模块,您根本无法确定模块中包含什么。


编辑,因为我仍然 被否决:其他答案正在回答一个不同的 问题,而不是被问到的问题。考虑以下因素:

import random, string

globals()['generated_' + random.choice(string.ascii_lowercase)] = "what's my name?"

print(sorted(globals()))

没有 方法可以猜测将创建哪些变量而不产生副作用。而且这种动态代码比较常见。

使用hasattr函数,其中returns函数是否存在:

示例 1)

hasattr(math,'tan')     --> true

示例 2)

hasattr(math,'hhhhhh')  --> false