3

How to check to which module a function belongs? Like,

check_module(sqrt)

Would return math and so on, if at all.

1 Answer 1

13

Functions have a __module__ attribute:

>>> from math import sqrt
>>> sqrt.__module__
'math'

You can use the inspect.getmodule() function to get the actual module object for a given object:

>>> from inspect import getmodule
>>> getmodule(sqrt)
<module 'math' from '/Users/mj/Development/Library/buildout.python/python-3.4/lib/python3.4/lib-dynload/math.so'>

inspect.getmodule() works for more than just functions and classes; it'll go through some length to find a module for a given object, based on the metadata on that object.

Sign up to request clarification or add additional context in comments.

7 Comments

For me (Python 2.7.3) >>> getmodule(math.sqrt) returns <module 'math' (built-in)>
@g4ur4v: math is a C-extension module, and it can either be compiled as a dynamically loaded library or made part of the Python binary itself. It looks like yours is compiled into the Python binary. built-in just means: no separate filename.
@g4ur4v getmodule(math.sqrt) assumes you know the module 'math' already, not the case here.
@AbdullahLeghari: even so, the result would not be any different; and just echoing math would also give the same output of course.
It's usually better to avoid "from" imports - this eliminates the problem.
|

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.