4

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.

1
  • Maybe you can try to import it then remove it from the sys.modules but I am not sure how it works. Commented Jul 31, 2015 at 20:44

4 Answers 4

6

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

example 1)

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

example 2)

hasattr(math,'hhhhhh')  --> false
Sign up to request clarification or add additional context in comments.

Comments

5

What about:

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

3 Comments

I like this ask for forgiveness approach!
This isn't exactly what I was asking for, but I think will work for the functionality that i was going for. Thank you.
@Rorschach - no worries. if I've helped you out please accept my answer. Thanks.
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.

4 Comments

would you call it a submodule if it is defined like this: def myfunction: ... Or would you call it a function?
That's a function. But you won't get that if you type import mymodule.myfunction. If you don't believe me, then after the import, print out information about myfunction after the import, e.g. print(mymodule.myfunction)
I believe you, I was just curious about which part I was wrong about.
The part that I quoted. You said that "you know that ... exists as a function because you can import it with ..." That's a confusing misstatement, because Python just doesn't work that way. If you want to import a function from a module, you can use from ... import, like in your accepted answer, but you just cannot do what you claimed you did in your question.
-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.

7 Comments

Absolutely not true. There are several packages that will let you inspect code without executing it.
@PatrickMaupin None of which can produce accurate results. Trust me, I'm working on one such package right now.
@o11c -- sure, it's impossible, just like the halting problem. But, then it's impossible if you import the module, as well. Even ModuleType can be subclassed, and the __item__ method replaced with something... The point is, for most normal code that is imported by most normal people, either one works fine, but neither one will work in all cases.
@PatrickMaupin This is a lot of real-world code that messes with the globals as a dict, or does glob imports, or performs multiple/conditional assignments / deletions, or ...
@o11c -- Absolutely. But you have to look at what the invoking real-world code might be interested in, as well. It typically won't be interested in every obscure deleted initialization function.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.