[Python-Dev] Alternative to more ABCs [was:] Iterable String Redux (aka String ABC)

Raymond Hettinger python at rcn.com
Sat May 31 14:25:11 CEST 2008


ISTM, the whole reason people are asking for a String ABC is so you can write isinstance(obj, String) and allow registered 
string-like objects to be accepted.

The downside is that everytime you want this for a concrete class or type, it is necessary to write a whole new ABC listing all of 
the required methods.  Also, you have to change all of the client code's isinstance tests from concrete to abstract.

I propose a simpler approach.  Provide an alternative registration function that overrides isinstance() so that objects can 
explicitly fake any concrete type:

  s = UserString('whiffleball')
  print isinstance(s, str)            --> False
  register_lookalike(UserString, str)
  print isinstance(s, str)            --> True

Besides saving us from writing tons of new ABCs, the approach works with existing code that already uses isinstance() with concrete 
types.

The ABCs that would remain are ones that are truly abstract, that define a generic interface (like mappings and sequences) and ones 
that offer some useful mixin behavior.  The remaining ABCs are ones where you have a fighting chance of actually being able to 
implement the interface (unlike String where it would be darned tricky to fully emulate encode(), split(), etc.)

This would completely eliminate the need for numbers.Integral for example.  AFAICT, its sole use case is to provide a way for 
numeric's integral types (like int8, int32) to pass themselves off as having the same API as regular ints.  Unfortunately, the 
current approach requires all consumer code to switch from isinstance(x,int) to isinstance(x,Integral).  It would be more useful if 
we could simply write register_lookalike(x,int) and be done with it (no need for numbers.py and its attendant abc machinery).

If we don't do this, then String won't be the last request.  People will want Datetime for example.  Pretty much any concrete type 
could have a look-a-like that wanted its own ABC and for all client code to switch from testing concrete types.


Raymond








More information about the Python-Dev mailing list