Print your python objects with objprint

Tian Gao
2 min readMar 14, 2021

--

Python’s built-in print function is not friendly with objects.

Say you have a class like:

class Position:
def __init__(self, x, y):
self.x = x
self.y = y

When you try to print an instance of it, you get something like

<__main__.Position object at 0x7f3289cabac0>

which is not helpful in most cases.

To solve it, normally we have to either print __dict__ attribute, or write a __str__ method of the class. However, writing __str__ function for every single class is too much work for quick debugging, and __dict__ is not flexible enough, not to mention it can’t deal with nested objects.

objprint is a light-weighted library that is specialized in printing arbitrary objects.

To use it, you need to install it from pip first.

pip install objprint

Then use objprint function from the library:

from objprint import objprintclass Position:
def __init__(self, x, y):
self.x = x
self.y = y
objprint(Position(1, 2))

Use objprint instead of print , you’ll get

<Position
.x = 1,
.y = 2
>

which is much more helpful than the default print function.

The good thing about objprint is, it can handle nested objects

from objprint import objprint

class Position:
def __init__(self, x, y):
self.x = x
self.y = y

class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)

objprint(Player())

With this more complicated example, objprint will print

<Player
.name = 'Alice',
.age = 18,
.items = ['axe', 'armor'],
.coins = {'gold': 1, 'silver': 33, 'bronze': 57},
.position = <Position
.x = 3,
.y = 5
>
>

objprint tries to achieve the best format for human-reading.

Sometimes, you want to overload the __str__ method and keep using the print function. You can use the decorator @add_objprint to the class.

@add_objprint
class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)

# This will print the same thing as above
print(Player())

Or, if you don’t like importing the library in every single file, you can install it so it’s globally accessible.

from objprint import install

# Now you can use objprint() in any file
install()

objprint is an open-source project and you can go to its github page to learn more about it.

--

--

Responses (1)