Making Variable Text Output More Pythonic?

I-T iqbaltalaat at gmail.com
Fri May 16 12:06:27 EDT 2008


A thousand apologies for my ignorance. I'll try not to get names mixed
up again in the future.

On May 16, 8:42 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> afrobeard <afrobe... at gmail.com> writes:
> > 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]
>
> ??? My suggestion is to get rid of attributes altogether and does not
> test any truth values.
>
>
>
> > 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 <arno... at googlemail.com> wrote:
> >> Casey <casey.mcgi... 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