display.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Unopinionated display configuration.
  3. """
  4. from __future__ import annotations
  5. import locale
  6. import sys
  7. from pandas._config import config as cf
  8. # -----------------------------------------------------------------------------
  9. # Global formatting options
  10. _initial_defencoding: str | None = None
  11. def detect_console_encoding() -> str:
  12. """
  13. Try to find the most capable encoding supported by the console.
  14. slightly modified from the way IPython handles the same issue.
  15. """
  16. global _initial_defencoding
  17. encoding = None
  18. try:
  19. encoding = sys.stdout.encoding or sys.stdin.encoding
  20. except (AttributeError, OSError):
  21. pass
  22. # try again for something better
  23. if not encoding or "ascii" in encoding.lower():
  24. try:
  25. encoding = locale.getpreferredencoding()
  26. except locale.Error:
  27. # can be raised by locale.setlocale(), which is
  28. # called by getpreferredencoding
  29. # (on some systems, see stdlib locale docs)
  30. pass
  31. # when all else fails. this will usually be "ascii"
  32. if not encoding or "ascii" in encoding.lower():
  33. encoding = sys.getdefaultencoding()
  34. # GH#3360, save the reported defencoding at import time
  35. # MPL backends may change it. Make available for debugging.
  36. if not _initial_defencoding:
  37. _initial_defencoding = sys.getdefaultencoding()
  38. return encoding
  39. pc_encoding_doc = """
  40. : str/unicode
  41. Defaults to the detected encoding of the console.
  42. Specifies the encoding to be used for strings returned by to_string,
  43. these are generally strings meant to be displayed on the console.
  44. """
  45. with cf.config_prefix("display"):
  46. cf.register_option(
  47. "encoding", detect_console_encoding(), pc_encoding_doc, validator=cf.is_text
  48. )