I have an object that's constructor accepts *kwargs and sets them as atributes.
class Observable(object):
def __init__(self, **kwargs):
for key in kwargs.keys():
setattr(self, key, kwargs[key])
I want print to represent the object in the following way:
>>> obs = Observable(foo=1, bar=5, _bazz=12, name='Amok', props=('One', 'two'))
>>> print(x)
Observable(bar=5, foo=1, name='Amok', props=('One', 'two'))
I tried to add a custom __repr__:
class Observable(object):
def __init__(self, **kwargs):
for key in kwargs.keys():
setattr(self, key, kwargs[key])
def __repr__(self):
atribs = [(atrib, self.__dict__[atrib]) for atrib in self.__dict__.keys() if not '_' == atrib[0]]
atrib_strs = []
for atrib, val in atribs:
atrib_strs.append('{}={}'.format(atrib, val))
out_str = '{}({})'.format(self.__class__.__name__, ', '.join(atrib_strs))
return out_str
For the input above it prints:
Observable(foo=1, bar=5, name=Amok, props=('One', 'two'))
My concern is that I have Amok instead of 'Amok'.
I can add a type check for strings, but perhaps there is a way to get a correct string representation of any python type? Maybe a standard library function?