Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to auto generate a __str__() implementation in python?

Being tired manually implementing a string representation for my classes, I was wondering if there is a pythonic way to do that automatically.

I would like to have an output that covers all the attributes of the class and the class name. Here is an example:

class Foo(object):     attribute_1 = None     attribute_2 = None     def __init__(self, value_1, value_2):          self.attribute_1 = value_1          self.attribute_2 = value_2 

Resulting in:

bar = Foo("baz", "ping") print(str(bar)) # desired: Foo(attribute_1=baz, attribute_2=ping) 

This question came to mind after using Project Lombok @ToString in some Java projects.

like image 961
Marco Ferrari Avatar asked Oct 02 '15 14:10

Marco Ferrari


1 Answers

You can iterate instance attributes using vars, dir, ...:

def auto_str(cls):     def __str__(self):         return '%s(%s)' % (             type(self).__name__,             ', '.join('%s=%s' % item for item in vars(self).items())         )     cls.__str__ = __str__     return cls  @auto_str class Foo(object):     def __init__(self, value_1, value_2):         self.attribute_1 = value_1          self.attribute_2 = value_2 

Applied:

>>> str(Foo('bar', 'ping')) 'Foo(attribute_2=ping, attribute_1=bar)' 
like image 183
falsetru Avatar answered Sep 23 '22 18:09

falsetru