Arnaud's code wont work if self.opt1 is None, an empty list, an empty tuple, False, etc, because all these evaluate to false. They wont print the internal state of these variables. [Just an informational notice, this may be the behavior you expect]
Secondly, I'm not sure if you know the variable names from before hand in which case Casey's approach will work, or you need to know them via introspection. http://www.ibm.com/developerworks/library/l-pyint.html [Scroll down to attributes]. On May 16, 1:44 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > Casey <[EMAIL PROTECTED]> writes: > > Hi, > > > I have some classes that print variable outputs depending on their > > internal state, like so: > > > def __str__(self): > > out = [] > > if self.opt1: out += ['option 1 is %s' % self.opt1'] > > if self.opt2: out += ['option 2 is %s' % self.opt2'] > > .... > > return '\n'.join(out) > > > Is there any way to make this cleaner? > > Maybe. > > Have a dictionary of options rather than individual attributes; > options not in the dictionary are not set. E.g. > > mask = { > 'opt1': 'option 1 is %s', > 'opt2': 'option 2 is %s', > ... > } > > def __str__(self): > return '\n'.join(mask[o] % v for o,v in self.options.iteritems()) > > -- > Arnaud -- http://mail.python.org/mailman/listinfo/python-list