Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customise the string representation of an object while debugging Python in VS Code

I'm trying to debug a pretty complex python script I'm working on in VS Code, and I've realised that my life would be a lot easier if the classes I'm using were represented in meaningful ways.

Currently, the debug panel represents my objects as things like <foo.Bar object at 0x000002C643F960A0>, but I'd much rather that I could specify how they should be presented, by overriding some function of it.

I've tried overriding the __str__() function to no avail. My googling sadly hasn't come up with anything useful.

Any ideas are appreciated!

Apologies if this is a repost - the similar questions thing isn't scrolling properly.

like image 770
Maddy Guthridge Avatar asked Jun 18 '26 12:06

Maddy Guthridge


1 Answers

This can be done by overriding the __repr__() method of the object.

class Person(object):
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    def __repr__(self) -> str:
        return f"Person({self.name=}, {self.age=})"

The __repr__() method is used by VS Code's debugger rather than the __str__() method, since __str__() is intended for user-facing representation and __repr__() is intended for debugging.

like image 125
Say OL Avatar answered Jun 20 '26 03:06

Say OL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!