Python, checking if a module has a certain function

时间:2015-07-31 20:26:54

标签: python python-2.7 import

I need to know if a python module function exists, without importing it.

Importing something that might not exist (not what I want): This is what I have so far, but it only works for whole modules not module functions.

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

The code above works for finding if the module exists, the code below is the functionality that I want, but this code doesn't work.

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

It gives this error:

No module named mymodule.myfunction

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

import mymodule.myfunction

But, I am aware that it is not a module, so this error does make sense, I just don't know how to get around it.

4 个答案:

答案 0 :(得分:5)

What about:

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

答案 1 :(得分:1)

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

import mymodule.myfunction

No -- if that works, then myfunction is a sub-module of the mymodule package.

You can import a module and inspect its vars(), or do a dir() on it, or even use a package like astor to inspect it without importing it. But your problem here would seem to be a lot more basic -- if you can type import mymodule.myfunction and not get an error, then myfunction is lying to you -- it's not really a function.

答案 2 :(得分:1)

使用hasattr函数,它返回函数是否​​存在:

例1)

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

例2)

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

答案 3 :(得分:-5)

What you want is impossible.

You fundamentally cannot determine what is in a module without executing it.


Edit since I'm still getting downvotes: the other answers are answering a different question, not the one that was asked. Consider the following:

import random, string

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

print(sorted(globals()))

There is no way to guess what variable(s) will be created without having the side-effects happen. And this kind of dynamic code is fairly common.