dir2.py 2.3 KB

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