/bangkokhotel/lib/python2.5/site-packages/django/utils/module_loading.py

https://bitbucket.org/luisrodriguez/bangkokhotel · Python · 69 lines · 55 code · 2 blank · 12 comment · 22 complexity · afc630466bf1b23f0e349a49d46f2132 MD5 · raw file

  1. import imp
  2. import os
  3. import sys
  4. def module_has_submodule(package, module_name):
  5. """See if 'module' is in 'package'."""
  6. name = ".".join([package.__name__, module_name])
  7. try:
  8. # None indicates a cached miss; see mark_miss() in Python/import.c.
  9. return sys.modules[name] is not None
  10. except KeyError:
  11. pass
  12. try:
  13. package_path = package.__path__ # No __path__, then not a package.
  14. except AttributeError:
  15. # Since the remainder of this function assumes that we're dealing with
  16. # a package (module with a __path__), so if it's not, then bail here.
  17. return False
  18. for finder in sys.meta_path:
  19. if finder.find_module(name, package_path):
  20. return True
  21. for entry in package_path:
  22. try:
  23. # Try the cached finder.
  24. finder = sys.path_importer_cache[entry]
  25. if finder is None:
  26. # Implicit import machinery should be used.
  27. try:
  28. file_, _, _ = imp.find_module(module_name, [entry])
  29. if file_:
  30. file_.close()
  31. return True
  32. except ImportError:
  33. continue
  34. # Else see if the finder knows of a loader.
  35. elif finder.find_module(name):
  36. return True
  37. else:
  38. continue
  39. except KeyError:
  40. # No cached finder, so try and make one.
  41. for hook in sys.path_hooks:
  42. try:
  43. finder = hook(entry)
  44. # XXX Could cache in sys.path_importer_cache
  45. if finder.find_module(name):
  46. return True
  47. else:
  48. # Once a finder is found, stop the search.
  49. break
  50. except ImportError:
  51. # Continue the search for a finder.
  52. continue
  53. else:
  54. # No finder found.
  55. # Try the implicit import machinery if searching a directory.
  56. if os.path.isdir(entry):
  57. try:
  58. file_, _, _ = imp.find_module(module_name, [entry])
  59. if file_:
  60. file_.close()
  61. return True
  62. except ImportError:
  63. pass
  64. # XXX Could insert None or NullImporter
  65. else:
  66. # Exhausted the search, so the module cannot be found.
  67. return False