Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, given a function name, how to get all the modules containing the function?

Tags:

python

For instance, there are os.path.walk, os.walk and assuming another md.walk, and assume os is imported but md is not. I desire a function like

whereis('walk')

while can return os.path.walk, os.walk and md.walk.

Or if it's difficult to know there is a md.walk, how to get the imported os.path.walk and os.walk?

like image 446
ddzzbbwwmm Avatar asked Sep 29 '22 01:09

ddzzbbwwmm


1 Answers

OK, that's was fun, here's updated solution. Some Python magic, solution for Python 2.7. Any improvements are welcome. It behaves like any other import - so be careful to wrap any of your executable code in if name == "__main__".

import inspect
import pkgutil
import sys

def whereis_in_globals(fname):
    return [m for m in sys.modules.itervalues()
            if module_has_function(m, fname)]

def whereis_in_locals(fname):
    modules = (__import__(module_name, globals(), locals(), [fname], -1)
               for _, module_name, _ in pkgutil.walk_packages(path="."))
    return [m for m in modules if module_has_function(m, fname)]

def module_has_function(m, fname):
    return hasattr(m, fname) and inspect.isfunction(getattr(m, fname))

if __name__ == "__main__":
    # these should never raise AttributeError
    for m in whereis_in_locals('walk'):
        m.walk
    for m in whereis_in_globals('walk'):
        m.walk
like image 136
Łukasz Rogalski Avatar answered Oct 30 '22 13:10

Łukasz Rogalski