Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 355
Rorschach Avatar asked Nov 01 '25 15:11

Rorschach


2 Answers

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

example 1)

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

example 2)

hasattr(math,'hhhhhh')  --> false
like image 76
Venkat Rajanala Avatar answered Nov 04 '25 10:11

Venkat Rajanala


What about:

try:
    from mymodule import myfunction
except ImportError:
    def myfunction():
        print("broken")
like image 30
Ewan Avatar answered Nov 04 '25 10:11

Ewan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!