Making Variable Text Output More Pythonic?

Arnaud Delobelle arnodel at googlemail.com
Thu May 15 16:44:38 EDT 2008


Casey <casey.mcginty at gmail.com> 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



More information about the Python-list mailing list