Search code examples
pythonpretty-printpython-telegram-bot

Python PrettyPrinter shows object address but not the contents


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?


Solution

  • 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()))