[Python-Dev] Mini-Pep: An Empty String ABC

Nick Coghlan ncoghlan at gmail.com
Mon Jun 2 12:47:08 CEST 2008


Guido van Rossum wrote:
> This PEP is incomplete without specifying exactly which built-in and
> stdlib types should be registered as String instances.
> 
> I'm also confused -- the motivation seems mostly "so that you can skip
> iterating over it when flattening a nested sequence" but earlier you
> rejected my "Atomic" proposal, saying "Earlier in the thread it was
> made clear that that atomicity is not an intrinsic property of a type;
> instead it varies across applications [...]". Isn't this String
> proposal just that by another name?
> 
> Finally, I fully expect lots of code writing isinstance(x, String) and
> making many more assumptions than promised by the String ABC. For
> example that s[0] has the same type as s (not true for bytes). Or that
> it is hashable (the Sequence class doesn't define __hash__). Or that
> s1+s2 will work (not in the Sequence class either). And many more.

I think the PEP also needs to explain why having multiple small one-off 
string ABCs is a bad thing. The whole point of providing a standard ABC 
mechanism is to enable exactly that: allowing a library to say "Here is 
my concept of what a string class needs to provide - register with this 
ABC to tell me that I can use your class without blowing up 
unexpectedly". The library can then preregister a bunch of other classes 
it knows about that do the right thing (such as the builtin str type)

That is, to write a flatten operation with ABC's you might do something 
along the lines of:

from abc import ABCMeta

class Atomic(metaclass=ABCMeta):
   """ABC for iterables that the flatten function will not expand"""

Atomic.register(str) # Consider builtin strings to be atomic

def flatten(obj, atomic=Atomic):
   itr = None
   if not isinstance(obj, atomic):
     try:
       itr = iter(obj)
     except (TypeError, AttributeError):
       pass
   if itr is not None:
     for item in itr:
       for x in flatten(item):
         yield x
   else:
     yield obj

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list