util.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License. See LICENSE in the project root
  3. # for license information.
  4. import inspect
  5. import os
  6. import sys
  7. def evaluate(code, path=__file__, mode="eval"):
  8. # Setting file path here to avoid breaking here if users have set
  9. # "break on exception raised" setting. This code can potentially run
  10. # in user process and is indistinguishable if the path is not set.
  11. # We use the path internally to skip exception inside the debugger.
  12. expr = compile(code, path, "eval")
  13. return eval(expr, {}, sys.modules)
  14. class Observable(object):
  15. """An object with change notifications."""
  16. observers = () # used when attributes are set before __init__ is invoked
  17. def __init__(self):
  18. self.observers = []
  19. def __setattr__(self, name, value):
  20. try:
  21. return super().__setattr__(name, value)
  22. finally:
  23. for ob in self.observers:
  24. ob(self, name)
  25. class Env(dict):
  26. """A dict for environment variables."""
  27. @staticmethod
  28. def snapshot():
  29. """Returns a snapshot of the current environment."""
  30. return Env(os.environ)
  31. def copy(self, updated_from=None):
  32. result = Env(self)
  33. if updated_from is not None:
  34. result.update(updated_from)
  35. return result
  36. def prepend_to(self, key, entry):
  37. """Prepends a new entry to a PATH-style environment variable, creating
  38. it if it doesn't exist already.
  39. """
  40. try:
  41. tail = os.path.pathsep + self[key]
  42. except KeyError:
  43. tail = ""
  44. self[key] = entry + tail
  45. def force_str(s, encoding, errors="strict"):
  46. """Converts s to str, using the provided encoding. If s is already str,
  47. it is returned as is.
  48. """
  49. return s.decode(encoding, errors) if isinstance(s, bytes) else str(s)
  50. def force_bytes(s, encoding, errors="strict"):
  51. """Converts s to bytes, using the provided encoding. If s is already bytes,
  52. it is returned as is.
  53. If errors="strict" and s is bytes, its encoding is verified by decoding it;
  54. UnicodeError is raised if it cannot be decoded.
  55. """
  56. if isinstance(s, str):
  57. return s.encode(encoding, errors)
  58. else:
  59. s = bytes(s)
  60. if errors == "strict":
  61. # Return value ignored - invoked solely for verification.
  62. s.decode(encoding, errors)
  63. return s
  64. def force_ascii(s, errors="strict"):
  65. """Same as force_bytes(s, "ascii", errors)"""
  66. return force_bytes(s, "ascii", errors)
  67. def force_utf8(s, errors="strict"):
  68. """Same as force_bytes(s, "utf8", errors)"""
  69. return force_bytes(s, "utf8", errors)
  70. def nameof(obj, quote=False):
  71. """Returns the most descriptive name of a Python module, class, or function,
  72. as a Unicode string
  73. If quote=True, name is quoted with repr().
  74. Best-effort, but guaranteed to not fail - always returns something.
  75. """
  76. try:
  77. name = obj.__qualname__
  78. except Exception:
  79. try:
  80. name = obj.__name__
  81. except Exception:
  82. # Fall back to raw repr(), and skip quoting.
  83. try:
  84. name = repr(obj)
  85. except Exception:
  86. return "<unknown>"
  87. else:
  88. quote = False
  89. if quote:
  90. try:
  91. name = repr(name)
  92. except Exception:
  93. pass
  94. return force_str(name, "utf-8", "replace")
  95. def srcnameof(obj):
  96. """Returns the most descriptive name of a Python module, class, or function,
  97. including source information (filename and linenumber), if available.
  98. Best-effort, but guaranteed to not fail - always returns something.
  99. """
  100. name = nameof(obj, quote=True)
  101. # Get the source information if possible.
  102. try:
  103. src_file = inspect.getsourcefile(obj)
  104. except Exception:
  105. pass
  106. else:
  107. name += f" (file {src_file!r}"
  108. try:
  109. _, src_lineno = inspect.getsourcelines(obj)
  110. except Exception:
  111. pass
  112. else:
  113. name += f", line {src_lineno}"
  114. name += ")"
  115. return name
  116. def hide_debugpy_internals():
  117. """Returns True if the caller should hide something from debugpy."""
  118. return "DEBUGPY_TRACE_DEBUGPY" not in os.environ
  119. def hide_thread_from_debugger(thread):
  120. """Disables tracing for the given thread if DEBUGPY_TRACE_DEBUGPY is not set.
  121. DEBUGPY_TRACE_DEBUGPY is used to debug debugpy with debugpy
  122. """
  123. if hide_debugpy_internals():
  124. thread.pydev_do_not_trace = True
  125. thread.is_pydev_daemon_thread = True