Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a object's value while debugging python in vscode?

What function (if any) should I implement so that VScode (or really python) can pick up the value of a user defined object in the VScode variable pane whilst debugging?

In this image you can see that arr shows up as [1, 2, 3, 4]. How can I get the variable node to show its value (1) instead of <__main__.ListNode object at 0x7f4a19eafb20>

like image 942
Jesse Avatar asked Oct 20 '25 05:10

Jesse


1 Answers

Since node is an object, its corresponding __repr__ method is returning that value by default. If you want to see the actual node value instead, then you can add a __repr__ method to ListNode class.

VScode uses the __repr__ method when showing the variable values. Here's a sample ListNode class with __repr__ method added -

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        return str(self.val)


node = ListNode(1)
print(node)

If you run this in VScode debug mode you would see the expected node value instead of <__main__.ListNode object at 0x101bed2b0>

Without __repr__ method - enter image description here

With __repr__ method - enter image description here

like image 175
Max Avatar answered Oct 21 '25 18:10

Max



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!