[Python-ideas] strings as iterables - from str.startswith taking any iterator instead of just tuple

Alexander Heger python at 2sn.net
Sat Jan 4 05:08:19 CET 2014


Dear Nick,

yes, defining an ABC for this case would be an excellent solution.

Thanks.

-Alexander

> However, I'm wondering if it might be reasonable to add a new entry in
> collections.abc for 3.5:
>
>>>> from abc import ABC
>>>> from collections.abc import Iterable
>>>> class Atomic(ABC):
> ...     @classmethod
> ...     def __subclasshook__(cls, subclass):
> ...         if not issubclass(subclass, Iterable):
> ...             return True
> ...         return NotImplemented
> ...
>>>> Atomic.register(str)
> <class 'str'>
>>>> Atomic.register(bytes)
> <class 'bytes'>
>>>> Atomic.register(bytearray)
> <class 'bytearray'>
>>>> isinstance(1, Atomic)
> True
>>>> isinstance(1.0, Atomic)
> True
>>>> isinstance(1j, Atomic)
> True
>>>> isinstance("Hello", Atomic)
> True
>>>> isinstance(b"Hello", Atomic)
> True
>>>> isinstance((), Atomic)
> False
>>>> isinstance([], Atomic)
> False
>>>> isinstance({}, Atomic)
> False
>
> Any type which wasn't iterable would automatically be considered
> atomic, while some types which *are* iterable could *also* be
> registered as atomic (with str, bytes and bytearray being the obvious
> candidates, as shown above).
>
> 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)
>
> Cheers,
> Nick.
>


More information about the Python-ideas mailing list