Implicit lists

Alex Martelli aleax at aleax.it
Thu Jan 30 16:28:33 EST 2003


holger krekel wrote:

> 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.

Not for an Italian forced to express himself _without_ moving
his hands about.

> However, it feels like an implicit kind of type-check.

Your feelings are a bit off here -- because types work
differently, e.g. UserString has NO type connection with
str -- but not by much: what it is is a PROTOCOL-check --
Python has no explicit notion of protocol but makes
substantial use of the notion under the cover (and if we
had protocol-adaptation in the language/library, life
would be sweeter).

Python does define (loosely) a sequence protocol, but,
alas for this case, strings and string-like thingies
also meet the sequence protocol and we DON'T want to
treat them as sequences in this context (and most other
application cases, in my limited experience and humble
opinion).  So we need to synthesize a "nonstringlike sequence
protocol" -- and for THAT, we need a "stringlike" protocol.

Identifying "stringlike" with "can be catenated to a
string" may seem like a daring leap, but think about
it for a second: why WOULD a non-stringlike sequence
ever WANT to be catenable to a string?  Your example:

> Maybe it's a "filename" class that allows iteration and
> allows __add__ with strings?

...seems somewhat far-fetched to me.  For any two
catenable sequences X and Y, given:

def catall(*n):
    for seq in n:
        for item in seq:
            yield item

surely catall(X, Y) should == catall(X + Y).  How
would this reasonable protocol constraint on sequence
catenation be met when X instantiates your hypothetical
class and Y is a string?


Alex





More information about the Python-list mailing list