Python: Equivelant of PHP functions print_r() or var_dump()

When migrating from PHP/Drupal to Python/Django, the lack of variable debugging can really impede your ability to get a feel for whats going on.

In PHP, I use print_r() and var_dump() type functions almost out of habit, just to see what information is being passed through to learn how things are working, or for debugging.

I havn't actually managed to find something that does the same in Python thing yet, but this comes pretty close so far. I'm sure someone can use this to work out what they need to do with it.

print dir(obj)

The output of the function varies, depending on the type of object being parsed.

a = [ 1, 2, 3, 4, 5 ]

print a
# Outputs [ 1, 2, 3, 4, 5 ]

print dir(a)
# Outputs all methods
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Now the best part about this function is that it also prints out the attributes of a the class instance.

class ExampleClass():
    title = "Title"
    description = "Description of something"

    def my_class_function(self):
        return [ 1, 2, 3 ]

Using dir() on an instance of that class would give:

c = ExampleClass()
print dir(c)
# Outputs
# ['__doc__', '__module__', 'description', 'my_class_function', 'title']

If anyone knows how to make it work better, feel free to let me know!

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog