1

In Node.js when I want to quickly check the value of something rather than busting out the debugger and stepping through, I quickly add a console.log(foo) and get a beautiful:

{
   lemmons: "pie",
   number: 9,
   fetch: function(){..}
   elements: {
      fire: 99.9
   }
}

Very clear! In Python I get this:

class LinkedList:
  head = None
  tail = None
  lemmons = 99

<__main__.LinkedList instance at 0x105989f80> or with vars(),

{}

or with dir(),

['_LinkedList__Node', '__doc__', '__module__', 'append', 'get_tail', 'head', 'lemmons', 'remove', 'tail']

Yuck! Look at all that nonsense - I thought python was supposed to be fast, beautiful and clean? Is this really how people do it? Do they implement customer str and custom repr for everything? Because that seems kind of crazy too..

Dylan Harness
  • 719
  • 1
  • 9
  • 20

3 Answers3

0

You can print your objects & Python classes in a lot of different ways, here's a simple one:

class LinkedList:
    head = None
    tail = None
    lemmons = 99

    def __str__(self):
        return str(vars(LinkedList))

print LinkedList()

I'd recommend you start for getting familiar with str and repr operators. In any case, this is a little example and with python there are tons of ways to pretty print object & classes

Community
  • 1
  • 1
BPL
  • 9,632
  • 9
  • 59
  • 117
0

The expectation is that you implement your own __str__ method so that you can pick what is important to log in your diags.

However, there is the option to log the whole object dictionary in a "pretty" format using a couple of lines of code. For example:

from pprint import pformat

class A(object):
    def __init__(self):
        self.foo = 1
        self.bar = {"hello": "world"}
        self._private = 0

a = A()
print pformat(vars(a))
# You can also pass pformat to your logger if that's what you have.

This will return something like this (depending on how much data you have and thw width constraint):

{'_private': 0,
 'bar': {'hello': 'world'},
 'foo': 1}
Peter Brittain
  • 13,489
  • 3
  • 41
  • 57
0

To expound on the above answers, mainly the one explaining str . Python repr() function returns the object representation in string format. This method is called when repr() “super class of str” function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

This will enhance your logs 10 fold if you implement this method well in any object