Type Hierarchies

Andrew Cooke andrew at andrewcooke.free-online.co.uk
Wed Feb 14 15:32:37 CET 2001


Often you can avoid testing types by making sure that all types that you
use implement whatever you require.  Rather than, for example, testing
for the type of something so that you can infer whether or not to use
len, it might be easier to include something that implements __len__
somewhere in the superclasses fo whatever you are manipulating.  DOn't
forget that Python has multiple inheritance, so this isn't hard (a lot
easier than Java!).

I don't know if it helps in your case, but it's a pretty standard way to
avoid tests with OO languages.  Sorry if I'm saying the obvious.

Andrew

Burkhard Kloss wrote:
> 
> Is there a way to check whether an object is a sequence? I'm not interested
> in the specific type, just that it qualifies as a sequence, so it could be
> built-in or user defined sequence. The language spec talks about type
> hierarchies, but if there's any way to access that concept in code I must
> have missed it.
> 
> Obviously I can try a call, and catch the exception:
> 
> def is_seq(a):
>     try:
>         len(a)
>         return 1
>     except:
>         return 0
> 
> which works:
> 
> assert is_seq( [] )
> assert is_seq( () )
> assert is_seq( "" )
> assert not is_seq( 1 )
> 
> but isn't very elegant.  It's probably also not very fast...
> 
> Am I missing something obvious here? Are there better ways?
> 
> Thanks,
> 
>     Burkhard



More information about the Python-list mailing list