I am quite new to Python. I am working on an application which uses lists of Datetime objects (from the datetime module).
I want to debug my app, so I print (or log) thoses lists, but it returns me this :
>>> print(list_with_datetimes_and_timedeltas) # print calls __str__ (by default), but list's __str__ calls the item's __repr__
[(None, 1, datetime.datetime(2020, 11, 1, 18, 44, 12, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Paris, Madrid'))), (datetime.timedelta(seconds=110, microseconds=7), 1, datetime.datetime(2020, 11, 1, 18, 46, 2, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Paris, Madrid'))), (datetime.timedelta(seconds=103, microseconds=5), 1, datetime.datetime(2020, 11, 1, 1) .....
Which is unreadable, and is due to the fact that the list.str() returns the repr of each items (from what I understood).
There is no problem with str of Datetimes and Timedeltas :
>>> print(my_list_with_datetimes_and_timedeltas[0][2])
2020-11-01 18:44:12+01:00 #which is what I would like in the list for the datetimes
>>> print(my_list_with_datetimes_and_timedeltas[1][0])
0:01:50.000007 #which is what I would like in the list for the timedeltas
I have thought about multiple solutions, but I really don't know how to choose and if they are even doable:
- change builtins List behavior so that it returns
__str__
representations of items instead of their__repr__
, because I don't really see why it would return__repr__
of objects if I call__str__
on a list (but this really doesn't seem a good idea, and I don't even know if it's doable) - change buildtins
__repr__
of Datetime objects in the module Datetime (also really doesn't seem to be a good idea) - as Dan said here, I can
print([str(item) for item in mylist])
, but I would have to do this for every line of every log every time I print a List (and it will not even work here because it is a list of tuple) - I also use a Logger (from logging). May it help if I change something there?
Do you have any solutions? (and reasons why Python chose that when we call str on a list it shows the repr of the items?)