Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check in which module a function is defined? Python

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

check_module(sqrt)

Would return math and so on, if at all.

like image 242
Abdullah Leghari Avatar asked May 31 '26 01:05

Abdullah Leghari


1 Answers

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.

like image 104
Martijn Pieters Avatar answered Jun 01 '26 14:06

Martijn Pieters



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!