Is 'isinstance()' the right thing?

James T. Dennis jadestar at idiom.com
Wed Jun 12 11:52:25 EDT 2002


Kragen Sitaker <kragen at pobox.com> wrote:

> juenglin at informatik.uni-freiburg.de (Ralf Juengling) writes:
>> Why aren't types not the right machinery for specifying the support 
>> of a protocol? ...

> The problem is that once you provide a mechanism for requiring
> arguments to be derived from a particular type, people will start
> requiring them to be derived from lots of different types, and some of
> those types won't be interface types.

> The result, in languages that support this, like C++ and Java, is
> tight coupling between classes: class A requires that arguments to its
> bletch() method be derived from class B, which typically means they
> have to inherit class B's bugs and stupid design mistakes, and also
> means that they have to be written by somebody who knew about class B.

> In one Python application I currently work on, we've been able to
> switch between using lists and Numeric arrays in several places with
> very little difficulty.

 However, we still want *some* way to use the introspection features
 in appropriate ways (sometimes for sanity checking, more often for
 application specific reasons).

 It seems like we can usually replace type tests with try: except:
 blocks or we can use hasattr() to test for the method or attribute
 that implements the desired object feature.  For example, the only
 sequence types for which hasattr(x,'isalpha') is true are the string
 and user string types.  Thus, if I want to write a generalized function
 that can recursively iterate over nested containers (lists , tuples, etc
 possibly CONTAINING lists, tuples, etc ad nauseum) but DON'T wish to 
 iterate over strings (which are iterable but are NOT really containers
 in most applications) then I can use hasattr(x,'isalpha') as a way to 
 stop my recursion.

 The problem with such generality is that there are always corner
 or unaccounted for cases.  For my "recursive container iteration" 
 example, I don't know what I'd use to avoid recursing into mmap objects
 if one of those were passed to me.  Maybe I'd want to interate on 
 file or database containers but NOT on chars in an mmap?  Obviously 
 this depends greatly on the task at hand.  If at all possible I'll
 restructure a specific case into an exception handling block.

 From what I can tell hasattr() should work through any form of GoF 
 Decorator, Adapter, Proxy or similar delegated composition objects 
 *iff* you can find the appropriate attribute to test for.

 Any thoughts on that?  Counterexamples?



 

 



More information about the Python-list mailing list