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

For example, there are os.path.walk , os.walk and another md.walk is assumed , and suppose os , but md is not. I need a function like

whereis('walk') 

while os.path.walk , os.walk and md.walk can be returned.

Or, if it's hard to find out, there is md.walk , how to get the imported os.path.walk and os.walk ?

+5
source share
2 answers

Well, that was fun, here is an updated solution. Some Python magic, a solution for Python 2.7. Any improvements are welcome. It behaves like any other import, so be careful to wrap any 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 
+3
source

Can you tell us more about your use case or larger goals? Getting an answer to non-importable modules is an interesting problem, and I don’t have an answer to how you formulated it, but depending on your actual use, you may be interested in determining if IDEs (integrated development environments) can do what you ask.

For example, if you install PyCharm (available free of charge in the community edition), you can enter the full or partial name of the function (just a text string), and then search in the active IDE project to see what you are looking for. For example, you can simply type “walk” on a line and then (IIR) click on it to see which possible modules can have the corresponding functions. You can also search in a different direction, seeing where the function is used in the project.

To search on a large scale, you may have to cheat a little and open your Python directory as a “project”, but it’s easy.

Again, you did not present a precedent, so apologize if you are specifically looking for, for example, a way to get this result for later use in the program. If you want you to be responsible for you as a developer and how you work, you can look at the tools you use to give an answer.

+1
source

All Articles