correct way to detect container type

Carlos Ribeiro carribeiro at gmail.com
Thu Oct 7 05:50:38 EDT 2004


On Thu, 07 Oct 2004 10:30:22 +0100, Robin Becker <robin at reportlab.com> wrote:
> I seem often to allow list/tuple arguments to be a singleton. This leads to code
> of the form
> 
> if type(arg) not in (type(()),type([])): arg = [arg]
> 
> or alternatively
> 
> from type import ListType, TupleType
> _seqTypes = ListType, TupleType
> ......
> if type(arg) not in _seqTypes: ....
> 
> is there a 'best' way to do this?

Depending upon the way you're using your sequence types, why don't you
check for __getitem__? As far as I'm aware, it's all that is needed to
support for loops. In some cases __len__ may also be needed. The
advantage is that you will accept any user defined type that supports
the sequence interface.


-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list