0

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.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • I've now discovered [Python Type Renderers](https://www.jetbrains.com/help/pycharm/customizing-views.html) in the PyCharm Debugger, but I can't make them work. They don't seem to have any effect whatsoever. I've tried restarting PyCharm, and various fiddling about to no avail. – Peter Wood Aug 22 '23 at 23:17
  • I did some quick experiments and noticed that the global `__package__` is `''` in a debugger run whereas that of a normal run is `None`. According to [this answer](https://stackoverflow.com/a/48833828), `__package__ == ''` is a sign of the file being imported as a top level module or similar. Does this work for you? – InSync Aug 23 '23 at 00:31
  • @InSync okay, that might work... I don't understand why it would be the case, but will have a try. I'll report back later... got some other more pressing matters to attend to. Thanks! – Peter Wood Aug 23 '23 at 08:59
  • 1
    @InSync unfortunately that didn't work. In the module where `MyClass` is defined, `__package__` has the proper package name and module name. However, I found [this question](https://stackoverflow.com/questions/333995/how-to-detect-that-python-code-is-being-executed-through-the-debugger) which says to check whether `pdb` has been imported, and that works for me. – Peter Wood Aug 24 '23 at 18:02

0 Answers0