Rorschach
Rorschach

Reputation: 3812

Python, checking if a module has a certain function

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.

Upvotes: 3

Views: 4301

Answers (4)

o11c
o11c

Reputation: 16156

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.

Upvotes: -5

Venkat Rajanala
Venkat Rajanala

Reputation: 129

Use hasattr function, which returns whether a function exists or not:

example 1)

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

example 2)

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

Upvotes: 5

Patrick Maupin
Patrick Maupin

Reputation: 8137

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.

Upvotes: 1

Ewan
Ewan

Reputation: 15068

What about:

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

Upvotes: 5

Related Questions