简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM