[Python-ideas] strings as iterables - from str.startswith taking any iterator instead of just tuple
Nick Coghlan
ncoghlan at gmail.com
Fri Jan 3 15:39:15 CET 2014
On 4 January 2014 00:21, spir <denis.spir at gmail.com> wrote:
> On 01/03/2014 12:41 PM, Nick Coghlan wrote:
>> Armed with such an ABC, you could then write an "iter_non_atomic"
>> helper function as:
>>
>> def iter_non_atomic(iterable):
>> if isinstance(iterable, Atomic):
>> raise TypeError("{!r} is considered
>> atomic".format(iterable.__class__.__name__)
>> return iter(iterable)
>
>
> I like this solution. But would live with checking for type (usually str).
The ducktyping variant I've also used on occasion is "hasattr(obj,
'encode')" rather than an instance check against a concrete type (it
also has the benefit of picking up both str and unicode in Python 2
when writing 2/3 compatible code that can't rely on basestring, as
well as UserString instances)
> The point is that, while not that uncommon, when the issue arises one has to
> deal with it at one or at most a few places in code (typically at start of
> one a few methods of a given type). It is not as if we had to carry an
> unneeded overload about everywhere.
Right, I see it as very similar to the "is that a sequence or a
mapping?" question that was one of the key motivations for adding the
ABC machinery in the first place. For that case, people historically
used a check like "hasattr(obj, 'keys')" (and I think we still do that
in a couple of places).
Here, the distinction is between true containers types like sets,
dicts and lists, and more structured iterables like strings, where the
whole is substantially more than the sum of its parts.
Actually, that would be another way of carving out the distinction -
rather than trying to cover *all* Atomic types, just have an
AtomicIterable ABC that indicated any structure where applying
operations like "flatten" doesn't make sense. In addition to str,
bytes and bytearray, memoryview and namedtuple instances would also be
appropriate candidates.
The Iterable suffix would indicate directly that this wasn't related
to concurrency.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list