Implicit lists

holger krekel pyth at devel.trillke.net
Thu Jan 30 20:23:06 CET 2003


Alex Martelli wrote:
> holger krekel wrote:
>    ...
> > I think it's safer to skip "iteration" with an explicit
> > 
> >     isinstance(arg, (str, unicode))
> > 
> > check.  It's also simpler to read and understand.
> 
> And it breaks *EVERY* use of UserString -- a module in the
> standard Python library, even!!! -- not to mention user-coded
> string-like types and classes.  *shudder*.

sorry, but fewer scream-emoticons would suffice to make 
your point.  

> A class is string-like if it acts like a string.

The problem is how to catch the string-likeness in
explicit terms.  You propose to execute 

    obj + 'somestring'

and see if it throws a type error.  To me this
definition of 'string-like' makes some sense but 
is arbitrary.  (At least you get problems with 
iterable objects that define an __add__ method which 
accepts strings, you know that).  

However, it feels like an implicit kind of type-check.  
The general pythonic "avoid checking for types, just
work with behaviour and catch exceptions" does not
really apply here.  We want to *prevent* something 
instead of react to erranonous behaviour.  

> def isstringlike(x):
>     try: return x+'!'
>     except TypeError: return False

This will often work, as you said.  But if this behaviour
is (in some way) exposed in a public API then users 
might get strange surprises when passing in their own stuff.
You never know what strange classes might get passed in.
Maybe it's a "filename" class that allows iteration and
allows __add__ with strings?  

regards,

    holger





More information about the Python-list mailing list