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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With