1

I am trying to pretty-print a python object by calling:

from pprint import pprint
...
pprint(update)

But the output looks like this:

<telegram.update.Update object at 0xffff967e62b0>

However, using Python's internal print() I get the correct output:

{'update_id': 14191809, 'message': {'message_id': 22222, 'date': 11111, 'chat': {'id': 00000, 'type': 'private', 'username': 'xxxx', 'first_name': 'X', 'last_name': 'Y'}, 'text': '/start', 'entities': [{'type': 'bot_command', 'offset': 0, 'length': 6}], 'caption_entities': [], 'photo': [], 'new_chat_members': [], 'new_chat_photo': [], 'delete_chat_photo': False, 'group_chat_created': False, 'supergroup_chat_created': False, 'channel_chat_created': False, 'from': {'id': 01010101, 'first_name': 'X', 'is_bot': False, 'last_name': 'Y', 'username': 'xxxx', 'language_code': 'en'}}}

Is there a way to make pprint(), show the object-data correctly and formatted?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Mortie
  • 316
  • 1
  • 4
  • 13
  • 1
    Does this answer your question? [Is there a built-in function to print all the current properties and values of an object?](https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a) – PacketLoss Feb 16 '21 at 00:42
  • 1
    `pprint(update.__str__())`? – CryptoFool Feb 16 '21 at 00:52
  • @PacketLoss Unfortunately the answers to that question do not provide the behavior I'm looking for. Still, the data printed by the `print()` function is more complete. – Mortie Feb 16 '21 at 00:53
  • @CryptoFool You can't `pprint` a string. Well, you can, but it will only line wrap it. Also don't call `__str__` directly but use `str(...)` instead. – Selcuk Feb 16 '21 at 00:57

1 Answers1

3

pprint uses the representation (__repr__() method) of the object while print uses __str__(). What you see in print output is not a dictionary but a string representation of the inner structure of the telegram.update.Update instance.

There is no generic solution to this, but since your question is about a specific library, consulting the relevant docs shows that there is a .to_json() method, so you can do this:

import json
from pprint import pprint

...
pprint(json.loads(update.to_json()))
Selcuk
  • 57,004
  • 12
  • 102
  • 110