dir2.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # encoding: utf-8
  2. """A fancy version of Python's builtin :func:`dir` function.
  3. """
  4. # Copyright (c) IPython Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. import inspect
  7. import types
  8. def safe_hasattr(obj, attr):
  9. """In recent versions of Python, hasattr() only catches AttributeError.
  10. This catches all errors.
  11. """
  12. try:
  13. getattr(obj, attr)
  14. return True
  15. except:
  16. return False
  17. def dir2(obj):
  18. """dir2(obj) -> list of strings
  19. Extended version of the Python builtin dir(), which does a few extra
  20. checks.
  21. This version is guaranteed to return only a list of true strings, whereas
  22. dir() returns anything that objects inject into themselves, even if they
  23. are later not really valid for attribute access (many extension libraries
  24. have such bugs).
  25. """
  26. # Start building the attribute list via dir(), and then complete it
  27. # with a few extra special-purpose calls.
  28. try:
  29. words = set(dir(obj))
  30. except Exception:
  31. # TypeError: dir(obj) does not return a list
  32. words = set()
  33. if safe_hasattr(obj, "__class__"):
  34. words |= set(dir(obj.__class__))
  35. # filter out non-string attributes which may be stuffed by dir() calls
  36. # and poor coding in third-party modules
  37. words = [w for w in words if isinstance(w, str)]
  38. return sorted(words)
  39. def get_real_method(obj, name):
  40. """Like getattr, but with a few extra sanity checks:
  41. - If obj is a class, ignore everything except class methods
  42. - Check if obj is a proxy that claims to have all attributes
  43. - Catch attribute access failing with any exception
  44. - Check that the attribute is a callable object
  45. Returns the method or None.
  46. """
  47. try:
  48. canary = getattr(obj, "_ipython_canary_method_should_not_exist_", None)
  49. except Exception:
  50. return None
  51. if canary is not None:
  52. # It claimed to have an attribute it should never have
  53. return None
  54. try:
  55. m = getattr(obj, name, None)
  56. except Exception:
  57. return None
  58. if inspect.isclass(obj) and not isinstance(m, types.MethodType):
  59. return None
  60. if callable(m):
  61. return m
  62. return None