Implicit lists

holger krekel pyth at devel.trillke.net
Thu Jan 30 12:53:21 EST 2003


Laura Creighton wrote:
> > Alex Martelli <aleax at aleax.it> writes:
> > 
> > > def iteron(something):
> > >     # string-like objects: treat as non-sequences
> > >     try: something+''
> > >     except TypeError: pass
> > >     else:
> > >         yield something
> > >         return
> > >     # other sequences
> > >     try:
> > >         for x in something: yield x
> > >     except TypeError:
> > >         yield something
> > 
> > I always thought that exceptions were expensive. Which makes me wonder
> > why you aren't using "isinstance(something, str)" for that first test.
> > 
> >         Thanks,
> >         <mike
> 
> > Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
> > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list
> 
> So when I pass it a string-like object I have made, the code just works.

In fact, your class needs to provide a

       def __add__(self, arg): 

method which needs to accepts strings.  If you are a true sequence (tm)
then instead you are forbidden to accept strings.  This is too much 
non-obvious impliciteness IMHO.

I think it's safer to skip "iteration" with an explicit

    isinstance(arg, (str, unicode))

check.  It's also simpler to read and understand.

regards,

    holger





More information about the Python-list mailing list