Question
Is there any way to detect that we are being run in the PyCharm debugger?
I want to disable some code, but only when the debugger's running.
Motivation
I have some objects which are proxies for data in a third-party proprietary library.
My proxy objects have string representations which are populated with values from the third party library.
When I hit a breakpoint and one of these objects is visible in the watch window, it displays the string representation, and this calls into the third-party library.
I don't know why it causes a crash. It used to be okay with Python 2, but with Python 3 it crashes.
I don't think the details of the third-party library are important to the question, I'm just describing how the problem manifests, to help understand why I need this solution:
Example code:
import third_party
class MyProxy:
def __init__(id_: int):
self._id = id_
def __str__(self):
return f"MyProxy(name={self.name})"
@property
def name(self):
return third_party.name(self._id)
Then, if in code I have an instance of MyProxy
, and I have a breakpoint within the scope of the name, the debugger crashes:
my_proxy = MyProxy(5)
a = 2 # breakpoint on this line causes a crash
If I remove the __str__
definition it's fine.
I want to be able to do something like:
def __str__(self):
if __debug__:
return f"MyProxy(id_={self._id})"
else:
return f"MyProxy(name={self.name})"
But this doesn't work because __debug__
is always True
unless we compile with -O
.