_exceptions.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import annotations
  2. import contextlib
  3. import inspect
  4. import os
  5. @contextlib.contextmanager
  6. def rewrite_exception(old_name: str, new_name: str):
  7. """
  8. Rewrite the message of an exception.
  9. """
  10. try:
  11. yield
  12. except Exception as err:
  13. if not err.args:
  14. raise
  15. msg = str(err.args[0])
  16. msg = msg.replace(old_name, new_name)
  17. args: tuple[str, ...] = (msg,)
  18. if len(err.args) > 1:
  19. args = args + err.args[1:]
  20. err.args = args
  21. raise
  22. def find_stack_level() -> int:
  23. """
  24. Find the first place in the stack that is not inside pandas
  25. (tests notwithstanding).
  26. """
  27. stack = inspect.stack()
  28. import pandas as pd
  29. pkg_dir = os.path.dirname(pd.__file__)
  30. test_dir = os.path.join(pkg_dir, "tests")
  31. for n in range(len(stack)):
  32. fname = stack[n].filename
  33. if fname.startswith(pkg_dir) and not fname.startswith(test_dir):
  34. continue
  35. else:
  36. break
  37. return n