The Python Oracle

object to string in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Object To String In Python
01:24 Accepted Answer Score 34
01:47 Answer 2 Score 3
01:58 Thank you

--

Full question
https://stackoverflow.com/questions/4367...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #tostring

#avk47



ACCEPTED ANSWER

Score 34


You can use __repr__ instead of __str__, which works recursively, although that is not a good idea most of the times (look at this answer for more details). Nevertheless, this works for me:

def __repr__(self):
    return str(self.__dict__)



ANSWER 2

Score 3


You can try using repr instead of str.

I got the below output for print(t1), when using def repr(self): instead of str.

{'attr1': 'bean 1', 'attr2': [{'attr1': 'bean 1.1', 'attr2': 'same'}, {'attr1': 'bean 1.2', 'attr2': 42}]}

Let me know if this solves your problem. Attaching image for reference.

Regards, Vinith